struts2-json-plugin插件实现异步通信
用例需要依赖的jar:
- struts2-core.jar
- struts2-convention-plugin.jar,非必须,
- struts2-json-plugin.jar
- org.codehaus.jackson.jar,提供json支持
用例代码如下:
- 数据库DDL语句
无
- struts.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> 3 <struts> 4 <package name="basePackage" extends="json-default"> 5 <!-- 未到找Action指向页面 --> 6 <default-action-ref name="404" /> 7 8 <global-exception-mappings> 9 <exception-mapping result="exception" exception="java.lang.Exception"></exception-mapping> 10 </global-exception-mappings> 11 12 <action name="404"> 13 <result type="dispatcher">/WEB-INF/jsp/error/error_page_404.jsp</result> 14 </action> 15 </package> 16 17 <!-- 入口地址:http://localhost:8888/struts2-test/test/gotoStruts2JsonPlugin.action --> 18 <package name="ajax" namespace="/test" extends="basePackage"> 19 <action name="struts2JsonPlugin" method="struts2JsonPlugin" 20 class="test.action.ajax.Struts2JsonPluginAction"> 21 <result type="json"> 22 <!-- 指定浏览器不缓存服务器响应 --> 23 <param name="noCache">true</param> 24 <!-- 指定不包括Action中值为null的属性 --> 25 <param name="excludeNullProperties">true</param> 26 </result> 27 </action> 28 </package> 29 </struts>
- java类
action类
BaseAction.java
1 package test.util; 2 import java.io.IOException; 3 import java.io.StringWriter; 4 import java.io.Writer; 5 import java.util.HashMap; 6 import java.util.Map; 7 import javax.servlet.ServletContext; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 import org.apache.log4j.Logger; 11 import org.apache.struts2.ServletActionContext; 12 import org.codehaus.jackson.JsonGenerator; 13 import org.codehaus.jackson.JsonProcessingException; 14 import org.codehaus.jackson.map.ObjectMapper; 15 import com.opensymphony.xwork2.ActionSupport; 16 17 public class BaseAction extends ActionSupport { 18 19 private static final long serialVersionUID = 4271951142973483943L; 20 21 protected Logger logger = Logger.getLogger(getClass()); 22 23 // 获取Attribute 24 public Object getAttribute(String name) { 25 return ServletActionContext.getRequest().getAttribute(name); 26 } 27 28 // 设置Attribute 29 public void setAttribute(String name, Object value) { 30 ServletActionContext.getRequest().setAttribute(name, value); 31 } 32 33 // 获取Parameter 34 public String getParameter(String name) { 35 return getRequest().getParameter(name); 36 } 37 38 // 获取Parameter数组 39 public String[] getParameterValues(String name) { 40 return getRequest().getParameterValues(name); 41 } 42 43 // 获取Request 44 public HttpServletRequest getRequest() { 45 return ServletActionContext.getRequest(); 46 } 47 48 // 获取Response 49 public HttpServletResponse getResponse() { 50 return ServletActionContext.getResponse(); 51 } 52 53 // 获取Application 54 public ServletContext getApplication() { 55 return ServletActionContext.getServletContext(); 56 } 57 58 // AJAX输出,返回null 59 public String ajax(String content, String type) { 60 try { 61 HttpServletResponse response = ServletActionContext.getResponse(); 62 response.setContentType(type + ";charset=UTF-8"); 63 response.setHeader("Pragma", "No-cache"); 64 response.setHeader("Cache-Control", "no-cache"); 65 response.setDateHeader("Expires", 0); 66 response.getWriter().write(content); 67 response.getWriter().flush(); 68 } catch (IOException e) { 69 e.printStackTrace(); 70 } 71 return null; 72 } 73 74 // AJAX输出文本,返回null 75 public String ajaxText(String text) { 76 return ajax(text, "text/plain"); 77 } 78 79 // AJAX输出HTML,返回null 80 public String ajaxHtml(String html) { 81 return ajax(html, "text/html"); 82 } 83 84 // AJAX输出XML,返回null 85 public String ajaxXml(String xml) { 86 return ajax(xml, "text/xml"); 87 } 88 89 // 根据字符串输出JSON,返回null 90 public String ajaxJson(String jsonString) { 91 return ajax(jsonString, "application/json"); 92 } 93 94 // 根据Map输出JSON,返回null 95 public String ajaxJson(Map<String, String> jsonMap) { 96 return ajax(mapToJson(jsonMap), "application/json"); 97 } 98 99 // 输出JSON成功消息,返回null 100 public String ajaxJsonSuccessMessage(String message) { 101 Map<String, String> jsonMap = new HashMap<String, String>(); 102 jsonMap.put("status", SUCCESS); 103 jsonMap.put("message", message); 104 return ajax(mapToJson(jsonMap), "application/json"); 105 } 106 107 // 输出JSON错误消息,返回null 108 public String ajaxJsonErrorMessage(String message) { 109 Map<String, String> jsonMap = new HashMap<String, String>(); 110 jsonMap.put("status", ERROR); 111 jsonMap.put("message", message); 112 return ajax(mapToJson(jsonMap), "application/json"); 113 } 114 // map转化为json数据 115 public String mapToJson(Map<String,String> map){ 116 ObjectMapper mapper = new ObjectMapper(); 117 Writer sw = new StringWriter(); 118 try { 119 JsonGenerator json = mapper.getJsonFactory().createJsonGenerator(sw); 120 json.writeObject(map); 121 sw.close(); 122 } catch (JsonProcessingException e) { 123 e.printStackTrace(); 124 } catch (IOException e) { 125 e.printStackTrace(); 126 } 127 return sw.toString(); 128 } 129 }
Struts2JsonPluginAction.java
1 package test.action.ajax; 2 import java.util.HashMap; 3 import java.util.Map; 4 import org.apache.struts2.json.annotations.JSON; 5 import test.util.BaseAction; 6 import com.opensymphony.xwork2.Action; 7 8 public class Struts2JsonPluginAction extends BaseAction 9 { 10 /** 11 * struts2-json-plugin 用例 12 */ 13 private static final long serialVersionUID = -4227395311084215139L; 14 // 模拟处理结果的属性 15 private int[] ints = {10, 20}; 16 private Map<String, String> map = new HashMap<String, String>(); 17 private String customName = "张三"; 18 // 封装请求参数的三个属性 19 private String field1; 20 private String field2; 21 22 // 没有setter和getter方法的字段不会被序列化 23 @SuppressWarnings("unused") 24 private String field3; 25 26 // 执行 27 public String struts2JsonPlugin() 28 { 29 map.put("name", "test"); 30 String test = getRequest().getParameter("field1"); 31 System.out.println("name:"+test); 32 return Action.SUCCESS; 33 } 34 35 // 使用注释语法来改变该属性序列化后的属性名 36 @JSON(name="newName") 37 public Map<String, String> getMap() 38 { 39 return this.map; 40 } 41 public int[] getInts() 42 { 43 return this.ints; 44 } 45 public void setCustomName(String customName) 46 { 47 this.customName = customName; 48 } 49 public String getCustomName() 50 { 51 return this.customName; 52 } 53 public void setField1(String field1) 54 { 55 this.field1 = field1; 56 } 57 public String getField1() 58 { 59 return this.field1; 60 } 61 public void setField2(String field2) 62 { 63 this.field2 = field2; 64 } 65 public String getField2() 66 { 67 return this.field2; 68 } 69 }
- jsp
1 <%@ page contentType="text/html; charset=GBK" language="java" errorPage="" %> 2 <%@ taglib prefix="s" uri="/struts-tags"%> 3 <% 4 request.setAttribute("cxtpath",request.getContextPath()); 5 %> 6 <!DOCTYPE html> 7 <html> 8 <head> 9 <meta name="author" content="" /> 10 <meta http-equiv="Content-Type" content="text/html; charset=GBK" /> 11 <title>使用Struts2JsonPlugin插件 </title> 12 <s:property value="cxtpath"/> 13 <script src="${cxtpath}/js/common/jquery-1.9.1.js" type="text/javascript"></script> 14 <script type="text/javascript"> 15 function struts2JsonPlugin() 16 { 17 // 以form1表单封装的请求参数发送请求。 18 $.post(‘${cxtpath}/test/struts2JsonPlugin.action‘, $("#form1").serializeArray(), 19 // data代表服务器响应,此处只是把服务器响应显示出来 20 function(data) { 21 console.log("data:"+JSON.stringify(data)); 22 for(var propName in data) 23 { 24 var temp = data[propName]; 25 if(propName == "newName"){ 26 console.log("name:"+temp["name"]) 27 }else{ 28 console.log(propName + " = " + temp); 29 } 30 } 31 } 32 ); 33 } 34 </script> 35 </head> 36 <body> 37 <div>使用Struts2JsonPlugin插件 38 <s:form id="form1" method="post"> 39 field1:<s:textfield name="field1" label="field1"/><br/> 40 field2:<s:textfield name="field2" label="field2"/><br/> 41 field3:<s:textfield name="field3" label="field3"/><br/> 42 <tr> 43 <td colspan="2"> 44 <input type="button" value="提交" onClick="struts2JsonPlugin();"/></td> 45 </tr> 46 </s:form> 47 </div> 48 </body> 49 </html>
环境:JDK1.6,MAVEN,tomcat,eclipse
源码地址:http://files.cnblogs.com/files/xiluhua/struts2-json-plugin.rar
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。