Struts 2+jquery+ajax Implements Transmitting List Data and Parsing

Posted by iluv8250 on Thu, 04 Jul 2019 22:51:55 +0200

In the last blog, we mentioned how to use struts2+jquery+ajax to realize the transmission of ordinary json data. In practice, the front desk not only shows the value after logical processing. There are also query values from the database, such as hibernate database, which return a List's data structure after the query operation is completed, so we need to convert the List into a json data type, and return it to the front desk, and then JS parse is displayed on the page.

Most of the code is the same as the previous blog, and the page is also a page.

First, a model class is established:
Mode.java

package com.action;

public class Mode {
    String name;
    int age;
    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;
    }

}

The model encapsulates attributes, and then constructs the generic List of the model

Next comes the action class
DemoListAction.java

package com.action;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;

import com.opensymphony.xwork2.ActionSupport;

public class DemoListAction extends ActionSupport {

    private String result;

    public String getResult() {
        return result;
    }
    public void setResult(String result) {
        this.result = result;
    }

    @Override
    public String execute() throws Exception {
        // TODO Auto-generated method stub

        List<Mode> list = new ArrayList<Mode>();
        Mode m1 = new Mode();
        m1.setName("oliver");
        m1.setAge(18);

        Mode m2 = new Mode();
        m2.setName("tommy");
        m2.setAge(20);

        Mode m3 = new Mode();
        m3.setName("thea");
        m3.setAge(16);

        list.add(m1);
        list.add(m2);
        list.add(m3);


        //Convert to JSONArray
        JSONArray jsonArray = JSONArray.fromObject(list);
        //To convert to String type, I'll explain that although the type of the following param is json, it doesn't affect that the actual parameter is a string.
        result = jsonArray.toString();

        return SUCCESS;
    }

}

Take a look at struts.xml, which is essentially the same as the previous one. Copy the previous one directly, and add the acion's instructions.

    <action name="demolistAction" class="com.action.DemoListAction">
            <result type="json">
                <! - The resu lt name here corresponds to the jsonObject in the action, and must have get,set methods - >.
                <param name="root">result</param>
            </result>
        </action>

Next is the front page.
It's very similar to the previous one, except that there are more json types parsed in the front desk.
index.jsp

<%@page import="java.text.SimpleDateFormat"%>
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%@taglib uri="/struts-tags" prefix="s" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    <script src="js/jquery.js" type="text/javascript"></script>
    <style type="text/css">
        .time{
            width:300px;
            background:#666;
        }
        .main{
            width:300px;
            height: 400px;
            background: #f60;
        }
    </style>
    <script type="text/javascript">
        function btn(){

            $.ajax({
                //Mode of submission
                type:"post",
                //Submitted Action
                url:"demoAction",
                data:{
                //Data submitted
                    name:$("input[name=name]").val(),
                    age:$("input[name=age]").val()
                },
                //Return data type
                dataType:"json",
                success:function(data){
                    //eval() is a method of parsing JSON strings into JSON data formats in JS
                    var str = JSON.stringify(data);
                    var d = eval(data);
                    //Put parsed de data into the corresponding id
                    //alert(str);
                    $("#s_name").text(""+d.name+"");
                    $("#s_age").text(""+d.age+"");
                },
                error:function(data)
                {
                    //Failure words
                    alert("fail");
                },
            });

        }
        function btn2(){

            $.ajax({
                //Mode of submission
                type:"post",
                //Submitted Action
                url:"demolistAction",
                data:{
                //Data submitted
                },
                //Return data type
                dataType:"json",
                success:function(data){
                    //alert(data);
                    var data2 = eval(data);
                    for(var i in data2)
                    {
                        //alert(data2[i].name);
                        $("#main").append("<br/>"+data2[i].name+":"+data2[i].age+"");
                    }
                },
                error:function(data)
                {
                    //Failure words
                    alert("fail");
                },
            });

        }

    </script>

  </head>

  <body>
    <div class="time" name="time">
        <% 
            SimpleDateFormat fomatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
            Date currentTime = new Date(); 
            String str = fomatter.format(currentTime); 
         %>
         <%=str %>
    </div>
    <form action="#" method = "post">
        name:<input type="text" name="name"/>
        age:<input type="text" name="age"/>
        <input type="button" class="btn" value="submit" onclick="btn()"/>
        <input type="button" class="btn" value="submit2" onclick="btn2()"/>
    </form>
    <div class="main" name="main" id="main">
        <span id="s_name">nnnn</span>
        <span id="s_age">aaaa</span>
    </div>
  </body>
</html>

Emphasize that it is not difficult to parse list type data in Json.
Next, run the screenshot:

The loop is appended to the corresponding div. With this method, the list found in the database can be displayed asynchronously.

Topics: JSON Java Database JSP