struts2实现jQuery的异步交互

时间:2023-03-09 16:01:52
struts2实现jQuery的异步交互

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

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

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

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

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

下面通过代码看一下:

Person属性映射表

 package com.action.xml;

 public class Person {

     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;
} }

客户端页面getJson.jsp代码:

 <%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%
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 'getJson.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(){
$("#button1").click(function(){
$.post("getJsonAction2.action",{name:$("#name").val()},function(returnedData,status){
var html = "<table width='60%' border='1' align='center'><tr><th>id</th><th>name</th><th>age</th><th>address</th></tr>"; 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></tr></table>"; $("#theBody table:eq(0)").remove();//找到id为theBody的body中的第0个table(即第一个table表)将其的内容删除掉,防止出现累加
$("#theBody").append(html);//将构建的HTML加入到id为theBody的body中 });
});
}) </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 information form server" id="button1">
</body>
</html>

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

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

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

 package com.action.json;

 import java.io.PrintWriter;

 import javax.servlet.http.HttpServletResponse;

 import org.apache.struts2.ServletActionContext;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter; import com.action.xml.Person;
import com.google.gson.Gson;
import com.opensymphony.xwork2.ActionSupport; @SuppressWarnings("serial")
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 { Person people = new Person(); people.setId(1);
people.setName(name);
people.setAge(20);
people.setAddress("beijing"); Gson gson = new Gson();
//通过Gson对象将Person对象内容以字符串格式返回
String result = gson.toJson(people); System.out.println(result); HttpServletResponse response = ServletActionContext.getResponse();
//设置http头,不使用浏览器缓冲
response.setHeader("cache-control", "no-cache");
//设置内容类型:xml异步交互是:“text/xml”;json异步交互此处是application/json
response.setContentType("application/json;charset=GB18030"); PrintWriter out = response.getWriter(); out.print(result); /*
OutputFormat format = OutputFormat.createCompactFormat();
format.setEncoding("GB18030"); XMLWriter writer = new XMLWriter(out, format); writer.write(result);*/ out.flush();
out.close(); return null;
}
}

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

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

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

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

GetJsonAction2.java代码
 package com.action.json;

 import org.apache.struts2.json.annotations.JSON;

 import com.opensymphony.xwork2.ActionSupport;

 @SuppressWarnings("serial")
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")//使用注解方式配置action
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 = "brijing"; return SUCCESS;
}
}

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

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

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

struts2实现jQuery的异步交互