Java Servlet generates JSON format data and displays it with jQuery, jsonjquery
1. Servlet uses json-lib to generate data in JSON format
Import java. io. IOException;
Import java. io. PrintWriter;
Import java. util .*;
Import javax. servlet. ServletException;
Import javax. servlet. annotation. WebServlet;
Import javax. servlet. http. HttpServlet;
Import javax. servlet. http. HttpServletRequest;
Import javax. servlet. http. HttpServletResponse;
Import json. Person;
Import net. sf. json. JSONArray;
Import net. sf. json. JSONObject;
@ WebServlet ("/JSONServlet ")
Public class JSONServlet extends HttpServlet {
Public JSONServlet (){
Super ();
}
Public void destroy (){
Super. destroy (); // Just puts "destroy" string in log
// Put your code here
}
Public void doGet (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException {
Response. setContentType ("application/x-json ");
Response. setCharacterEncoding ("GBK ");
PrintWriter out = response. getWriter ();
ArrayList <Person> items = new ArrayList <Person> ();
Items. add (new Person (2, "jack "));
Items. add (new Person (2, "bob "));
Items. add (new Person (2, "alex "));
JSONArray jsonArray = new JSONArray ();
JsonArray. addAll (items );
Out. print (jsonArray. toString ());
}
Public void doPost (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException {
DoGet (request, response );
}
Public void init () throws ServletException {
// Put your code here
}
}
2. Front-end Page code
<% @ Page language = "java" contentType = "text/html; charset = ISO-8859-1"
PageEncoding = "ISO-8859-1" %>
<! DOCTYPE html PUBLIC "-// W3C // dtd html 4.01 Transitional // EN" "http://www.w3.org/TR/html4/loose.dtd">
<Html>
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = ISO-8859-1">
<Title> Insert title here </title>
<Script type = "text/javascript" src = "js/jquery-1.10.2.min.js"> </script>
<Script type = "text/javascript">
$ (Document). ready (
Function (){
$ ("# Kick"). click (
Function (){
$. Ajax ({
Type: "post", // post method
Url: "JSONServlet ",
Data :{
"Legs": "2 ",
"Name": "aa"
},
// Callback function for ajax success
Success: function (returnData ){
Var arr = eval (returnData );
$. Each (arr, function (index, content ){
$ ("# Result"). append (
"<Div>" + content. legs
+ "</Div>" + "<div>"
+ Content. name
+ "</Div>
});
}
});
});
});
</Script>
</Head>
<Body>
<Input type = "button" id = "kick" value = "kick">
<Div id = "result"> </div>
</Body>
</Html>