码迷,mamicode.com
首页 > Web开发 > 详细

struts2实现jQuery的异步交互

时间:2017-12-17 15:50:46      阅读:275      评论:0      收藏:0      [点我收藏+]

标签:href   click   this   ref   param   images   odi   styles   eth   

struts2中jQuery的异步交互有两种方式:

1)是利用构造字符串的方式来实现;

    使用该方法主要是在服务器端根据前端的请求,返回一个字符串信息,然后前端的jQuery通过解析该字符串信息得到对应的请求内容。该方法优点是使用比较灵活,缺点是使用比较复杂。

2)是利用struts自带的jQuery插件来实现。

    使用插件方法时,其过程比较简单,和配置普通action信息一样。需要构造XXXset和XXXget方法以及execute方法。然后在struts.xml文件中配置action。该方法优点是使用简单,缺点是:需要在action中定义出前端页面中可能要获取的所有属性信息,使用起来不够灵活。

下面通过代码看一下:

Person属性映射表

 1 package com.action.xml;
 2 
 3 public class Person {
 4 
 5     private int id;
 6     private String name;
 7     private int age;
 8     private String address;
 9     public int getId() {
10         return id;
11     }
12     public void setId(int id) {
13         this.id = id;
14     }
15     public String getName() {
16         return name;
17     }
18     public void setName(String name) {
19         this.name = name;
20     }
21     public int getAge() {
22         return age;
23     }
24     public void setAge(int age) {
25         this.age = age;
26     }
27     public String getAddress() {
28         return address;
29     }
30     public void setAddress(String address) {
31         this.address = address;
32     }
33     
34 }

客户端页面getJson.jsp代码:

 1 <%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11     
12     <title>My JSP ‘getJson.jsp‘ starting page</title>
13     <script type="text/javascript" src="scripts/jquery-1.4.4.js"></script>
14     <meta http-equiv="pragma" content="no-cache">
15     <meta http-equiv="cache-control" content="no-cache">
16     <meta http-equiv="expires" content="0">    
17     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
18     <meta http-equiv="description" content="This is my page">
19     <!--
20     <link rel="stylesheet" type="text/css" href="styles.css">
21     -->
22     
23     <script type="text/javascript">
24      
25        $(function(){
26            $("#button1").click(function(){
27                $.post("getJsonAction2.action",{name:$("#name").val()},function(returnedData,status){
28                    var html = "<table width=‘60%‘ border=‘1‘ align=‘center‘><tr><th>id</th><th>name</th><th>age</th><th>address</th></tr>";
29                    
30                    
31                        var people = returnedData;
32                        var id = people.id;
33                        var name = people.name;
34                        var age = people.age;
35                        var address = people.address;
36                        
37                        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></tr></table>";
38                 
39                     $("#theBody table:eq(0)").remove();//找到id为theBody的body中的第0个table(即第一个table表)将其的内容删除掉,防止出现累加
40                     $("#theBody").append(html);//将构建的HTML加入到id为theBody的body中
41                        
42                });
43            });
44        })
45     
46     </script>
47   </head>
48   
49   <body id="theBody">
50     
51     <select id="name">
52         <option value="zhangsan">zhangsan</option>
53         <option value="lisi">lisi</option>
54     </select>
55     <input type="button" value="get json information form server" id="button1">   
56   </body>
57 </html>

以上代码是两种方式都会使用的公共代码

(1)首先是通过构造字符串实现异步交互代码:

注意:需要在WebRoot目录中导入jQuery库

 1 package com.action.json;
 2 
 3 import java.io.PrintWriter;
 4 
 5 import javax.servlet.http.HttpServletResponse;
 6 
 7 import org.apache.struts2.ServletActionContext;
 8 import org.dom4j.io.OutputFormat;
 9 import org.dom4j.io.XMLWriter;
10 
11 import com.action.xml.Person;
12 import com.google.gson.Gson;
13 import com.opensymphony.xwork2.ActionSupport;
14 
15 @SuppressWarnings("serial")
16 public class GetJsonAction extends ActionSupport {
17 
18     
19     private String name;
20 
21     public String getName() {
22         return name;
23     }
24 
25     public void setName(String name) {
26         this.name = name;
27     }
28     
29     @Override
30     public String execute() throws Exception {
31         
32         Person people = new Person();
33         
34         people.setId(1);
35         people.setName(name);
36         people.setAge(20);
37         people.setAddress("beijing");
38         
39         Gson gson = new Gson();
40         //通过Gson对象将Person对象内容以字符串格式返回
41         String result = gson.toJson(people);
42         
43         System.out.println(result);
44         
45         HttpServletResponse response = ServletActionContext.getResponse();
46         //设置http头,不使用浏览器缓冲
47         response.setHeader("cache-control", "no-cache");
48         //设置内容类型:xml异步交互是:“text/xml”;json异步交互此处是application/json
49         response.setContentType("application/json;charset=GB18030");
50         
51         PrintWriter out = response.getWriter();
52         
53         out.print(result);
54         
55         /*
56         OutputFormat format = OutputFormat.createCompactFormat();
57         format.setEncoding("GB18030");
58         
59         XMLWriter writer = new XMLWriter(out,  format);
60         
61         writer.write(result);*/
62     
63         out.flush();
64         out.close();
65     
66         return null;
67     }
68 }

Struts.xml配置文件的配置信息

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE struts PUBLIC
 3     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
 4     "http://struts.apache.org/dtds/struts-2.3.dtd">
 5 <struts>
 6     <!-- 设置Struts运行模式为开发者模式,如果value为false则关闭开发者模式 -->
 7     <constant name="struts2.devMode" value="true"></constant>
 8     
 9     <package name="struts2_ajax" namespace="/" extends="struts-default">
10         
11         
12         <action name="getJsonAction" class="com.action.json.GetJsonAction">
13         
14         </action>      
15         
16     </package>
17 </struts>

(2) 通过struts中的json插件实现交互代码:

说明:使用插件的方式需要导入struts给提供的struts2-json-plugin-2.3.24.jar插件

GetJsonAction2.java代码
 1 package com.action.json;
 2 
 3 import org.apache.struts2.json.annotations.JSON;
 4 
 5 import com.opensymphony.xwork2.ActionSupport;
 6 
 7 @SuppressWarnings("serial")
 8 public class GetJsonAction2 extends ActionSupport {
 9 
10     private String name;
11     
12     private int id;
13     
14     private int age;
15     
16     private String address;
17 
18     public String getName() {
19         return name;
20     }
21 
22     public void setName(String name) {
23         this.name = name;
24     }
25 
26     public int getId() {
27         return id;
28     }
29 
30     public void setId(int id) {
31         this.id = id;
32     }
33 
34     //@JSON(name="myAge")//使用注解方式配置action
35     public int getAge() {
36         return age;
37     }
38 
39     public void setAge(int age) {
40         this.age = age;
41     }
42 
43     public String getAddress() {
44         return address;
45     }
46 
47     public void setAddress(String address) {
48         this.address = address;
49     }
50     
51     @Override
52     public String execute() throws Exception {
53         
54         this.id = 1;
55         this.age = 30;
56         this.address = "brijing";
57 
58         return SUCCESS;
59     }
60 }

struts.xml配置文件的配置信息

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE struts PUBLIC
 3     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
 4     "http://struts.apache.org/dtds/struts-2.3.dtd">
 5 <struts>
 6     <!-- 设置Struts运行模式为开发者模式,如果value为false则关闭开发者模式 -->
 7     <constant name="struts2.devMode" value="true"></constant>
 8     
 9     <package name="struts2_ajax" namespace="/" extends="json-default"><!-- 使用json插件是需要继承json-default -->
10         
11         <!-- 利用struts的json插件 -->
12         <action name="getJsonAction2" class="com.action.json.GetJsonAction2">
13             <result name="success" type="json">
14                 <!-- 如果有不需要获取的属性则需要使用以下语句过滤掉不需要的属性 -->
15                 <!-- <param name="excludeProperties">address</param> -->
16             </result>
17   
18         </action>
19     </package>
20 </struts>

 

以上两种方式运行结果一样:

技术分享图片

 

struts2实现jQuery的异步交互

标签:href   click   this   ref   param   images   odi   styles   eth   

原文地址:http://www.cnblogs.com/lihuibin/p/8052067.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!