zoukankan      html  css  js  c++  java
  • Struts2实现异步调用机制详细剖析(XML和JSON)

    一、使用XML传递

    1、页面展示getXML.jsp
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
    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 'getXML.jsp' starting page</title>
     
        <script type="text/javascript" src="scripts/jquery-1.4.4.js"></script>
     
        <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 type="text/javascript">
     
        function getInfo()
        {
            $.post("getXMLAction.action",
            {
                name: $("#name").val()//像后台getXMLAction.action中传递name值
            },function(returnedData, status)
            {
                var id = $(returnedData).find("id").text();//使用find函数取得后台传递的XML信息
                var name = $(returnedData).find("name").text();
                var age = $(returnedData).find("age").text();
                var address = $(returnedData).find("address").text();
     
                var html = "<table width='60%' border='1' align='center'><tr><th>id</th><th>name</th><th>age</th><th>address</th><tr align='center'><td>" + id + "</td><td>" + name + "</td><td>" + age + "</td><td>" + address + "</td></tr></table>";
     
                $("#theBody table:eq(0)").remove();//表示每次将table表格中的第一行清除掉,进行添加,显示为每次显示一条结果
     
                $("#theBody").append(html);
            });       
        }
        </script>
     
      </head>
     
        <body id="theBody">
     
       <select id="name">
     
        <option value="zhangsan">zhangsan</option>
        <option value="lisi">lisi</option>
     
       </select>  
     
        <input type="button" value="get information" onclick="getInfo();">
      </body>
    </html>
    2、配置struts
    <action name="getXMLAction" class="com.shengsiyuan.action.xml.GetXMLAction">
    </action>
    3、bean对象Person.java
    package com.shengsiyuan.action.xml;
     
    public class People
    {
        private int id;
     
        private String name;
     
        private int age;
     
        private String address;
     
        public int getId()
        {
            return id;
        }
     
        public void setId(int id)
        {
            this.id = id;
        }
     
        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 getAddress()
        {
            return address;
        }
     
        public void setAddress(String address)
        {
            this.address = address;
        }
    }
    4、GetXMLAction.java用于处理请求和返回请求
    package com.shengsiyuan.action.xml;
    import java.io.PrintWriter;
    import javax.servlet.http.HttpServletResponse;
    import org.apache.struts2.ServletActionContext;
    import org.dom4j.Document;
    import org.dom4j.DocumentHelper;
    import org.dom4j.Element;
    import org.dom4j.io.OutputFormat;
    import org.dom4j.io.XMLWriter;
    import com.opensymphony.xwork2.ActionSupport;
    public class GetXMLAction extends ActionSupport
    {
        private String name;
     
        public String getName()
        {
            return name;
        }
     
        public void setName(String name)
        {
            this.name = name;
        }
     
        @Override
        public String execute() throws Exception
        {
            //zhang san
            People people1 = new People();
     
            people1.setId(1);
            people1.setName("zhangsan");
            people1.setAge(30);
            people1.setAddress("beijing");
     
            People people2 = new People();
     
            people2.setId(2);
            people2.setName("lisi");
            people2.setAge(50);
            people2.setAddress("tianjin");
     
            Document document = DocumentHelper.createDocument();//dom4j中的document对象
     
            Element rootElement = document.addElement("persons");//使用element来定义XML
     
            rootElement.addComment("This is comment!!");
     
            Element e = rootElement.addElement("person");//根元素为person
     
            Element idElement = e.addElement("id");//子元素对应关系
            Element nameElement = e.addElement("name");
            Element ageElement = e.addElement("age");
            Element addressElement = e.addElement("address");
     
            if("zhangsan".equals(name))
            {
                idElement.setText(people1.getId() + "");
                nameElement.setText(people1.getName());
                ageElement.setText(people1.getAge() + "");
                addressElement.setText(people1.getAddress());
            }
            else
            {
                idElement.setText(people2.getId() + "");
                nameElement.setText(people2.getName());
                ageElement.setText(people2.getAge() + "");
                addressElement.setText(people2.getAddress());
            }
     
            HttpServletResponse response = ServletActionContext.getResponse();
     
            response.setContentType("text/xml; charset=utf-8");
            response.setHeader("cache-control", "no-cache");
     
            PrintWriter out = response.getWriter();
     
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding("utf-8");
     
            XMLWriter writer = new XMLWriter(out, format);
     
            writer.write(document);
     
            out.flush();
            out.close();
     
            return null;//返回空值,这里对应struts处无result对应的返回值
        }
    }
    5、对应的XML输出信息
     

    二、使用json异步获取信息

    1、页面getJson.jsp
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
    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 'json.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 type="text/javascript" src="scripts/jquery-1.4.4.js"></script>
     
        <script type="text/javascript">
     
        $(function()
        {
            $("#button1").click(function()
            {
                $.post("getJsonAction2.action",{name: $("#name").val()},
                    function(returnedData, status)
                {
                    var people = returnedData;
     
                    var id = people.id;
                    var name = people.name;
                    var age = people.age;
                    var address = people.address;
     
                    var html = "<table width='60%' border='1' align='center'><tr><th>id</th><th>name</th><th>age</th><th>address</th><tr align='center'><td>" + id + "</td><td>" + name + "</td><td>" + age + "</td><td>" + address + "</td></tr></table>";
     
                    $("#theBody table:eq(0)").remove();
     
                    $("#theBody").append(html);
     
                });           
            });
        });
     
        </script>
     
     
      </head>
     
      <body id="theBody">
     
       <select id="name">
     
        <option value="zhangsan">zhangsan</option>
        <option value="lisi">lisi</option>
     
       </select
     
     
        <input type="button" value="get json content from server" id="button1">
     
      </body>
    </html>
    2、struts控p制层
            <action name="getJsonAction" class="com.shengsiyuan.action.json.GetJsonAction">
            </action>
    3、bean对象Person.java见使用XML获取后台信息
    4、GetJsonAction.java处理信息的action
    package com.shengsiyuan.action.json;
     
    import java.io.PrintWriter;
     
    import javax.servlet.http.HttpServletResponse;
     
    import org.apache.struts2.ServletActionContext;
     
    import com.google.gson.Gson;
    import com.opensymphony.xwork2.ActionSupport;
    import com.shengsiyuan.action.xml.People;
     
    public class GetJsonAction extends ActionSupport
    {
        private String name;
     
        public String getName()
        {
            return name;
        }
     
        public void setName(String name)
        {
            this.name = name;
        }
     
        @Override
        public String execute() throws Exception
        {
            People people = new People();
     
            people.setId(1);
            people.setName(name);
            people.setAge(30);
            people.setAddress("beijing");
     
            Gson gson = new Gson();
     
            String result = gson.toJson(people);
     
            HttpServletResponse response = ServletActionContext.getResponse();
     
            response.setContentType("application/json; charset=utf-8");
            response.setHeader("cache-control", "no-cache");
     
            PrintWriter out = response.getWriter();
     
            out.print(result);
     
            out.flush();
            out.close();
     
            return null;
        }
    }
    5、以下是Json打印出的json数据

    三、使用struts插件获得json数据信息

     
    此插件解压缩中对应xml文件信息如下:返回一个json的结果于对应的类进行过处理,而且还定义啦一个json拦截器
     
    1、页面中和以上页面相同
    2、struts配置
    <package name="struts2_ajax" extends="json-default"><!-- 其中更改继承为json-default-->
    <action name="getJsonAction2" class="com.shengsiyuan.action.json.GetJsonAction2">
                <result name="success" type="json">
     
                    <param name="excludeProperties">address</param><!--这里表示你不想传递到页面的变量-->
     
                </result>
            </action>
    </package>
     3、GetJsonAction2.java处理​信息的action
    package com.shengsiyuan.action.json;
     
    import org.apache.struts2.json.annotations.JSON;
     
    import com.opensymphony.xwork2.ActionSupport;
     
    public class GetJsonAction2 extends ActionSupport
    {
        private String name;
     
        private int id;
     
        private int age;
     
        private String address;
     
        public String getName()
        {
            return name;
        }
     
        public void setName(String name)
        {
            this.name = name;
        }
     
        public int getId()
        {
            return id;
        }
     
        public void setId(int id)
        {
            this.id = id;
        }
     
        @JSON(name="myAge")//这里演示的是注解更改为我们想要的名字,那在页面中我们就要用myAge,可以不使用注解
        public int getAge()
        {
            return age;
        }
     
        public void setAge(int age)
        {
            this.age = age;
        }
     
        public String getAddress()
        {
            return address;
        }
     
        public void setAddress(String address)
        {
            this.address = address;
        }
     
        @Override
        public String execute() throws Exception
        {
            this.id = 1;
            this.age = 30;
            this.address = "beijing";
     
            return SUCCESS;//由于使用了struts插件我们这里返回success
        }
    }





  • 相关阅读:
    webpack学习笔记五
    webpack的学习使用四
    判断数组B是否为数组A的子集
    html5标签知多少
    图代文时隐藏文字的兼容实现
    负margin的移位参考线
    font-size 兼容问题
    IE6读取不到样式文件bug
    一个重构眼中的“项目管理”
    唯物 VS 唯心
  • 原文地址:https://www.cnblogs.com/wang3680/p/3283761.html
Copyright © 2011-2022 走看看