2. JSP-Sample with JSON-Object

HTML-Teil

    <script type="text/javascript">
       // <![CDATA[
      "use strict";

      var xmlhttp = new XMLHttpRequest();
       // verbinde XMLHttpRequest mit der "Event-Methode"
      xmlhttp.onreadystatechange = readajax;

      function  testajax( form ) {
        "use strict";
          // Aufruf 
         xmlhttp.open("GET", "TestAjax01.php?parameter=wert");
         xmlhttp.send(null);
      }

       function readajax() {
         "use strict";
         var elementajax = document.getElementById("ajax");
         if (xmlhttp.readyState == 4) {
           elementajax.innerHTML = xmlhttp.responseText;
         }
         else {
           alert(xmlhttp.readyState);
         }
       }

      // ]]>
    </script>

  </head>

<body>
  <form>
    <input type="button" value="Send" onclick="testajax(this.form)"/>
  </form>
   <div id="ajax"> </div>
</body>
</html>
</div>

JSP-Teil


<%@ 
  page import = "java.util.* " 
%>

<%@ 
  page import = "java.text.* " 
%>

<%

<%@ page import = "java.lang.reflect.* " %>


<%!

  private String getJSon(Object obj) {
     StringBuilder sb = new StringBuilder();
     try {     
       Class c = obj.getClass();
       Field[] fields; 
       fields = c.getDeclaredFields();
        // {  {"name": "Meier59", "mnr":12345} 
       sb.append("{");
       int n=fields.length-1;
       for(int i=0; i<n; i++) {
         Field field = fields[i];
         sb.append("\"");
         sb.append(field.getName());
         sb.append("\": ");
         String s=field.getType().toString();
         if (s.indexOf("String")>0) {
            sb.append("\"");
            sb.append(field.get(obj));
            sb.append("\"");
         }
         else {
          sb.append(field.get(obj));
         }
         if (i<n-1) {
            sb.append(", ");
         }
       }
       sb.append("}");
       }
     catch ( IllegalAccessException e) {
     }
     return sb.toString();
  }
 
  private class Student  {
   public String name="";
   public int mnr=0;

   public Student  () {
   }

   public Student(String name, int mnr) {
      this.name = name;
      this.mnr = mnr;
   }

   public String toString() {
     return name+", "+mnr;
   }

   public String getJSon() {
     return "{\"name\": \""+name+"\", \"mnr\":"+mnr+"}";
   }

} // class Student

%> 

<%@ page import = "java.util.* " %>
<%@ page import = "java.text.* " %>


<%
  String name = "Meier" + min;
  int mnr = 12345;
  
  Student std = new Student(name, mnr);

  String ergebnis = "Ergebnis: " + std;
  // niw get my own JSONObject, obly one call
  ergebnis = getJSon(std);
  out.println(ergebnis);

%>

 
%>





Druckbare Version


1. JSP Sample
NEW JSon-Object