用例需要依赖的jar:
- struts2-core.jar
- struts2-convention-plugin.jar,非必须,
- struts2-json-plugin.jar
- org.codehaus.jackson.jar,提供json支持
用例代码如下:
- 数据库DDL语句
无
- 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.0.dtd">
<struts>
<package name="basePackage" extends="json-default">
<!-- 未到找Action指向页面 -->
<default-action-ref name="404" /> <global-exception-mappings>
<exception-mapping result="exception" exception="java.lang.Exception"></exception-mapping>
</global-exception-mappings> <action name="404">
<result type="dispatcher">/WEB-INF/jsp/error/error_page_404.jsp</result>
</action>
</package> <!-- 入口地址:http://localhost:8888/struts2-test/test/gotoStruts2JsonPlugin.action -->
<package name="ajax" namespace="/test" extends="basePackage">
<action name="struts2JsonPlugin" method="struts2JsonPlugin"
class="test.action.ajax.Struts2JsonPluginAction">
<result type="json">
<!-- 指定浏览器不缓存服务器响应 -->
<param name="noCache">true</param>
<!-- 指定不包括Action中值为null的属性 -->
<param name="excludeNullProperties">true</param>
</result>
</action>
</package>
</struts>
- java类
action类
BaseAction.java
package test.util;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.ObjectMapper;
import com.opensymphony.xwork2.ActionSupport; public class BaseAction extends ActionSupport { private static final long serialVersionUID = 4271951142973483943L; protected Logger logger = Logger.getLogger(getClass()); // 获取Attribute
public Object getAttribute(String name) {
return ServletActionContext.getRequest().getAttribute(name);
} // 设置Attribute
public void setAttribute(String name, Object value) {
ServletActionContext.getRequest().setAttribute(name, value);
} // 获取Parameter
public String getParameter(String name) {
return getRequest().getParameter(name);
} // 获取Parameter数组
public String[] getParameterValues(String name) {
return getRequest().getParameterValues(name);
} // 获取Request
public HttpServletRequest getRequest() {
return ServletActionContext.getRequest();
} // 获取Response
public HttpServletResponse getResponse() {
return ServletActionContext.getResponse();
} // 获取Application
public ServletContext getApplication() {
return ServletActionContext.getServletContext();
} // AJAX输出,返回null
public String ajax(String content, String type) {
try {
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType(type + ";charset=UTF-8");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.getWriter().write(content);
response.getWriter().flush();
} catch (IOException e) {
e.printStackTrace();
}
return null;
} // AJAX输出文本,返回null
public String ajaxText(String text) {
return ajax(text, "text/plain");
} // AJAX输出HTML,返回null
public String ajaxHtml(String html) {
return ajax(html, "text/html");
} // AJAX输出XML,返回null
public String ajaxXml(String xml) {
return ajax(xml, "text/xml");
} // 根据字符串输出JSON,返回null
public String ajaxJson(String jsonString) {
return ajax(jsonString, "application/json");
} // 根据Map输出JSON,返回null
public String ajaxJson(Map<String, String> jsonMap) {
return ajax(mapToJson(jsonMap), "application/json");
} // 输出JSON成功消息,返回null
public String ajaxJsonSuccessMessage(String message) {
Map<String, String> jsonMap = new HashMap<String, String>();
jsonMap.put("status", SUCCESS);
jsonMap.put("message", message);
return ajax(mapToJson(jsonMap), "application/json");
} // 输出JSON错误消息,返回null
public String ajaxJsonErrorMessage(String message) {
Map<String, String> jsonMap = new HashMap<String, String>();
jsonMap.put("status", ERROR);
jsonMap.put("message", message);
return ajax(mapToJson(jsonMap), "application/json");
}
// map转化为json数据
public String mapToJson(Map<String,String> map){
ObjectMapper mapper = new ObjectMapper();
Writer sw = new StringWriter();
try {
JsonGenerator json = mapper.getJsonFactory().createJsonGenerator(sw);
json.writeObject(map);
sw.close();
} catch (JsonProcessingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sw.toString();
}
}
Struts2JsonPluginAction.java
package test.action.ajax;
import java.util.HashMap;
import java.util.Map;
import org.apache.struts2.json.annotations.JSON;
import test.util.BaseAction;
import com.opensymphony.xwork2.Action; public class Struts2JsonPluginAction extends BaseAction
{
/**
* struts2-json-plugin 用例
*/
private static final long serialVersionUID = -4227395311084215139L;
// 模拟处理结果的属性
private int[] ints = {10, 20};
private Map<String, String> map = new HashMap<String, String>();
private String customName = "张三";
// 封装请求参数的三个属性
private String field1;
private String field2; // 没有setter和getter方法的字段不会被序列化
@SuppressWarnings("unused")
private String field3; // 执行
public String struts2JsonPlugin()
{
map.put("name", "test");
String test = getRequest().getParameter("field1");
System.out.println("name:"+test);
return Action.SUCCESS;
} // 使用注释语法来改变该属性序列化后的属性名
@JSON(name="newName")
public Map<String, String> getMap()
{
return this.map;
}
public int[] getInts()
{
return this.ints;
}
public void setCustomName(String customName)
{
this.customName = customName;
}
public String getCustomName()
{
return this.customName;
}
public void setField1(String field1)
{
this.field1 = field1;
}
public String getField1()
{
return this.field1;
}
public void setField2(String field2)
{
this.field2 = field2;
}
public String getField2()
{
return this.field2;
}
}
- jsp
<%@ page contentType="text/html; charset=GBK" language="java" errorPage="" %>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%
request.setAttribute("cxtpath",request.getContextPath());
%>
<!DOCTYPE html>
<html>
<head>
<meta name="author" content="" />
<meta http-equiv="Content-Type" content="text/html; charset=GBK" />
<title>使用Struts2JsonPlugin插件 </title>
<s:property value="cxtpath"/>
<script src="${cxtpath}/js/common/jquery-1.9.1.js" type="text/javascript"></script>
<script type="text/javascript">
function struts2JsonPlugin()
{
// 以form1表单封装的请求参数发送请求。
$.post('${cxtpath}/test/struts2JsonPlugin.action', $("#form1").serializeArray(),
// data代表服务器响应,此处只是把服务器响应显示出来
function(data) {
console.log("data:"+JSON.stringify(data));
for(var propName in data)
{
var temp = data[propName];
if(propName == "newName"){
console.log("name:"+temp["name"])
}else{
console.log(propName + " = " + temp);
}
}
}
);
}
</script>
</head>
<body>
<div>使用Struts2JsonPlugin插件
<s:form id="form1" method="post">
field1:<s:textfield name="field1" label="field1"/><br/>
field2:<s:textfield name="field2" label="field2"/><br/>
field3:<s:textfield name="field3" label="field3"/><br/>
<tr>
<td colspan="2">
<input type="button" value="提交" onClick="struts2JsonPlugin();"/></td>
</tr>
</s:form>
</div>
</body>
</html>
环境:JDK1.6,MAVEN,tomcat,eclipse
源码地址:http://files.cnblogs.com/files/xiluhua/struts2-json-plugin.rar