Userservlet. java code
Package com. iss. servlet;
Import org. json. JSONException;
Import org. json. JSONObject;
Import com. iss. pojo. User;
Import com. iss. util. JSONUtil;
Public class UserServlet extends HttpServlet {
Public void doGet (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException {
DoPost (request, response );
}
Public void doPost (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException {
Response. setContentType ("text/html; charset = UTF-8 ");
// Add objects to a list
List <User> userList = new ArrayList <User> ();
User user1 = new User ("Zhang San", "male", "18 ");
User user2 = new User ("Li Si", "male", "19 ");
User user3 = new User ("Wang Wu", "male", "20 ");
UserList. add (user1 );
UserList. add (user2 );
UserList. add (user3 );
PrintWriter out = response. getWriter ();
String str = null;
Try {
// Return the list to the interface if the Account Password Matches
If (request. getParameter ("userName"). equals ("jquery ")
& Request. getParameter ("password"). equals ("ajax ")){
Str = JSONObject. quote (JSONUtil. toJSONString (userList ));
}
Out. print (str );
} Catch (JSONException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
System. out. println ("str" + str );
Out. flush ();
Out. close ();
}
}
Html code
<Body>
Account jquery password ajax
<Form id = "mainform">
<Ul>
<Li>
Account
<Input type = "text" name = "userName"/>
</Li>
<Li>
Password
<Input type = "password" name = "password"/>
</Li>
<Li>
<Input onclick = "login ()" type = "button" value = "login"/>
</Li>
</Ul>
</Form>
Queried data
<Div id = "diva">
</Div>
<Script type = "text/javascript">
Function login (){
// Obtain the form parameters
Var args = $ ("# mainform"). serialize ();
// Call jquery's json Retrieval Method
// The three parameters are the Request Path, request parameters, and the callback function for the returned data.
$. GetJSON ("servlet/UserServlet", args, function (data ){
If (data! = Null ){
// The interface returns a json string. Call JSON. parse () to convert the data to json.
// Format object
Var jsondata = JSON. parse (data );
ParseData (jsondata );
} Else {
Alert ("incorrect account and password ");
}
})
}
Function parseData (data ){
Var str = "";
// Traverse data in json format
For (var key in data ){
Strstrstr = str + "user" + data [key]. userName + "age" + data [key]. age + "<br/>"
Alert (str );
}
// Add data to div
$ ("# Diva" pai.html (str );
}
</Script>
</Body>
Www.2cto.com
UserServlet remember to import tool class JSONStringObject JSONUtil
Jsp imports jquery. js and json. js
Author: Wang defeng-chinlang