IT Band of Brothers JavaWeb tutorial AJAX and JSON string classic case

Case needs: AJAX client sends a request to the server to obtain user data information.

Case realization:

On the server side Java objects you want to convert JSON string, if you use JSON string splicing way is very tedious, and very error-prone, so generally use third-party Jar package to help us put Java object-oriented programming JSON string.

When a single terminal Java object using a static method JSONObject JSON string class in the server: formObject (Object object), the method returns a JSONObject object, call the object's toString () method to complete the conversion.

Client JSON string into JavaScript objects, commonly used methods as follows:

● use the eval function:

var jsonStr = '{"id":1,"name":"张三"}';
var obj = eval( " ( " + str + " ) " );

● Use JSON.parse function

var jsonStr = '{"id":1,"name":"张三"}';
var obj = JSON.parse(str);

You may find it easier to use JSON.parse function of the JSON string into a JavaScript object, which is the recommended way.

The following example demonstrates how to use Ajax to query a user information from the server and use json-lib.jar kit to convert user objects to JSON string is then returned to the client.

First create a new dynamic Web project, the project called xdl_ajax_demo, after the success of the project to build add json-lib.jar and its dependencies in the lib directory:

●  commons-beanutils.jar

●  commons-collections.jar

●  common-logging.jar

●  common-lang.jar

●  ezmorph.jar

●  json-lib.jar

Com.xdl.bean then create a User class and define package at the package, to encapsulate user data, comprising the following properties:

name: Name

age: Age

gender: gender

salary: salary

Detailed code User class is as follows:

com.xdl.bean Package Penalty for; 
public class {the User 
    Private String name; // Name 
    private int age; // the age 
    private String gender; // Gender 
    private double salary; // salary 
    / ** 
     * Constructor 
     * @param name 
     * Age @param 
     * @param Gender 
     * @param the salary 
     * / 
    public the User (String name, int Age, Gender String, Double the salary) { 
        this.name = name; 
        this.age = Age; 
        this.gender = Gender; 
        this.salary the salary =; 
    } 
    / ** 
     * no argument constructor 
     * / 
    public the User () {  
    }
    // the Set and the Get method
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    public double getSalary() {
        return salary;
    }
    public void setSalary(double salary) {
        this.salary = salary;
    }
}

Next, define a new com.xdl.servlet package and the package GetUserInfoServlet class can return User object JSON string data. Detailed code is as follows:

package com.xdl.servlet;
import com.xdl.bean.User;
import net.sf.json.JSONObject;
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 java.io.IOException;
@WebServlet("/getUserInfo")
public class GetUserInfoServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request,
          HttpServletResponse response) throws ServletException, IOException {
        User user = new User("三十画生",26,"男",5000.0);
        String jsonStr = JSONObject.fromObject(user).toString();
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(jsonStr);
    }
    @Override
    protected void doPost(HttpServletRequest request,
           HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}

HTML pages User.html prepared, using Ajax transmission request, the user information returned JSON string is parsed to display the page. Detailed code is as follows:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript">
        function getUserInfo(){
            var xhr = window.XMLHttpRequest ?
                     new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHttp");
            xhr.open('get','getUserInfo',true);
            xhr.onreadystatechange = function(){
                if(xhr.readyState == 4 && xhr.status == 200){
                    var userInfo = xhr.responseText;
                    userInfo = JSON.parse(userInfo);
                    document.getElementById("name").innerHTML =
                         'name:' + userInfo.name;
                    document.getElementById("age").innerHTML =
                         'age:' + userInfo.age;
                    document.getElementById("gender").innerHTML =
                         'gender:' + userInfo.gender;
                    document.getElementById("salary").innerHTML =
                         'salary:' + userInfo.salary;
                }
            };
            xhr.send(null);
        }
    </script>
</head>
<body>
    <button type="button" onclick="getUserInfo()">获取用户信息</button>
    <h2 id="name"></h2>
    <h2 id="age"></h2>
    <h2 id="gender"></h2>
    <h2 id="salary"></h2>
</body>
</html>

Finally, start the Tomcat server, and then open the browser and type http: // localhost: 8080 / xdl_ajax_ demo / user.html, the browser will display the page shown in Figure 4.

Then click on the user information acquiring button, the page will be sent Ajax request for user information, and finally the browser displays the page shown in Figure 5, showing browser has obtained user data returned from the server JSON format, has been successfully resolved and .

1240

图 4 user.html                

1240

5 page successfully receive and parse user information returned from the server

Case needs: in one case, a client sends an AJAX request, the server returns all user information.

Case realization:

Java server side set into static method JSONArray JSON string class requires: formObject (Object object), the method returns a JSONArray object, call the object's toString () method to complete the conversion.

The following will be carried out on the basis of prior xdl_ajax_demo project, demonstrates how to use Ajax to query a list of user information from the server and use json-lib.jar kit converts the user a list of objects to JSON string is then returned to the client.

First class is defined at com.xdl.servlet GetUserInfoListServlet package, you may be returned JSON string data User object collection. Detailed code is as follows:

package com.xdl.servlet;
import com.xdl.bean.User;
import net.sf.json.JSONArray;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@WebServlet("/getUserInfoList")
public class GetUserInfoListServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request,
          HttpServletResponse response) throws ServletException, IOException {
        User user1 = new User("三十画生",26,"男",5000.0);
        User user2 = new User("二十画生",24,"女",15000.0);
        List<User> userList = new ArrayList<>();
        userList.add(user1);
        userList.add(user2);
        String jsonStr = JSONArray.fromObject(userList).toString();
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(jsonStr);
    }
    @Override
    protected void doPost(HttpServletRequest request,
          HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}

编写HTML页面userlist.html,使用Ajax发送请求,把返回的用户信息列表的JSON字符串经过解析后显示到页面上。详细代码如下:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript">
        function getUserInfoList(){
            var xhr = window.XMLHttpRequest ?
                     new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHttp");
            xhr.open('get','getUserInfoList',true);
            xhr.onreadystatechange = function(){
                if(xhr.readyState == 4 && xhr.status == 200){
                    var userInfoList = xhr.responseText;
                    userInfoList = JSON.parse(userInfoList);
                    var userInfoListTable =
                                document.getElementById("userInfo List");
                    userInfoListTable.innerText = '';
                    var rowHead = userInfoListTable.insertRow();
                    rowHead.insertCell().innerHTML = 'NAME';
                    rowHead.insertCell().innerHTML = 'AGE';
                    rowHead.insertCell().innerHTML = 'GENDER';
                    rowHead.insertCell().innerHTML = 'SALARY';
                    for(var i = 0;i<userInfoList.length;i++){
                        var userInfo = userInfoList[i];
                        var row = userInfoListTable.insertRow();
                        row.insertCell().innerHTML = userInfo.name;
                        row.insertCell().innerHTML = userInfo.age;
                        row.insertCell().innerHTML = userInfo.gender;
                        row.insertCell().innerHTML = userInfo.salary;
                    }
                }
            }
            xhr.send(null);
        }
    </script>
</head>
<body>
    <button type="button" onclick="getUserInfoList()">获取用户信息列表</button>
    <table id="userInfoList"></table>
</body>
</html>

Finally, start the Tomcat server, and then open the browser and type http: // localhost: 8080 / xdl_ajax_ demo / userlist.html, the browser will display the page shown in Figure 6.

Then click on the button to obtain the user information list, the page sends a request to obtain the user information list Ajax, and finally the browser displays the page as shown in FIG. 7, showing the user browser has obtained the list of data returned by the server JSON format, and It has been successfully resolved.

1240

Figure 6 userlist.html

1240

7 page successfully receive and parse a list of user information returned from the server


Guess you like

Origin blog.51cto.com/14311187/2405683