struts2,实现Ajax异步通信

用例需要依赖的jar:

  1. struts2-core.jar
  2. struts2-convention-plugin.jar,非必须
  3. 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 }

Struts2AjaxAction.java

 1 package test.action.ajax;
 2 import java.io.UnsupportedEncodingException;
 3 import java.util.HashMap;
 4 import java.util.Map;
 5 import org.apache.commons.lang3.StringUtils;
 6 import org.apache.struts2.convention.annotation.Action;
 7 import org.apache.struts2.convention.annotation.Namespace;
 8 import org.apache.struts2.convention.annotation.ParentPackage;
 9 import org.apache.struts2.convention.annotation.Result;
10 import test.util.BaseAction;
11 
12 @ParentPackage("ajax")
13 @Namespace("/test")
14 public class Struts2AjaxAction extends BaseAction
15 {
16     /**
17      * struts2-ajax 用例
18      */
19     private static final long serialVersionUID = -4227395311084215139L;
20     
21     @Action(value = "gotoStruts2JsonPlugin", results = { 
22     @Result(name = "success", location = "/WEB-INF/content/test/ajax/struts2JsonPlugin.jsp")})
23     public String gotoStruts2JsonPlugin()
24     {
25         return SUCCESS;
26     }
27     
28     @Action(value = "gotoStruts2Ajax_post", results = { 
29     @Result(name = "success", location = "/WEB-INF/content/test/ajax/struts2Ajax_post.jsp")})
30     public String struts2Ajax_post()
31     {
32         return SUCCESS;
33     }
34 
35     @Action(value = "gotoStruts2Ajax_ajax", results = { 
36     @Result(name = "success", location = "/WEB-INF/content/test/ajax/struts2Ajax_ajax.jsp")})
37     public String struts2Ajax_ajax()
38     {
39         return SUCCESS;
40     }
41     
42     @Action(value = "post")
43     public String post()
44     {
45         String f1 = StringUtils.defaultString(getRequest().getParameter("field1"));
46         String f2 = StringUtils.defaultString(getRequest().getParameter("field2"));
47         ajaxText(f1+",测试,"+f2);
48         return null;
49     }
50     
51     @Action(value = "ajax")
52     public String ajax() throws UnsupportedEncodingException
53     {
54         String f1 = StringUtils.defaultString(getRequest().getParameter("field1"));
55         String f2 = StringUtils.defaultString(getRequest().getParameter("field2"));
56 
57         Map<String, String> jsonMap = new HashMap<String, String>();
58         jsonMap.put(f1, f1);
59         jsonMap.put(f2, f2);
60         jsonMap.put("status", SUCCESS);
61         super.ajaxJson(jsonMap);
62         return null;
63     }
64 }
  • jsp

struts2Ajax_post.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>使用$.ajax提交Ajax请求</title>
<s:property value="cxtpath"/>
<script src="${cxtpath}/js/common/jquery-1.9.1.js" type="text/javascript"></script>
<script type="text/javascript">
function ajax()
{
    // 以form1表单封装的请求参数发送请求。
    var val1 = $("#form1_field1").val();
    var val2 = $("#form1_field2").val();
    $.ajax({
        url: '${cxtpath}/test/ajax.action', 
        data: {"field1": val1,"field2": val2},
        dataType: "json",
        async: false,
        type: "POST",
        success: function(data) {
            console.log("data:"+JSON.stringify(data));
            if (data.status == "success") {
                console.log("succ");
            }else{
                data;
                console.log("fail");
            }
        }
    });
}
</script>
</head>
<body>
<div>使用$.ajax提交Ajax请求
<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="ajax();"/></td>
    </tr>
</s:form>
</div>
</body>
</html>

struts2Ajax_ajax.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>使用$.post提交Ajax请求</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 post()
16 {
17     // 以form1表单封装的请求参数发送请求。
18     $.post('${cxtpath}/test/post.action', $("#form1").serializeArray(),
19         // data代表服务器响应,此处只是把服务器响应显示出来
20         function(data) {
21             console.log("data:"+JSON.stringify(data));
22         }
23     )
24 }
25 </script>
26 </head>
27 <body>
28 <div>使用$.post提交Ajax请求
29 <s:form id="form1" method="post">
30     field1:<s:textfield name="field1" label="field1"/><br/>
31     field2:<s:textfield name="field2" label="field2"/><br/>
32     field3:<s:textfield name="field3" label="field3"/><br/>
33     <tr>
34         <td colspan="2">
35         <input type="button" value="提交" onClick="post();"/></td>
36     </tr>
37 </s:form>
38 </div>
39 </body>
40 </html>

 

环境:JDK1.6,MAVEN,tomcat,eclipse

源码地址:https://files.cnblogs.com/files/xiluhua/struts2-Ajax.rar

 

posted @ 2015-04-03 14:47  xiluhua  阅读(2350)  评论(0编辑  收藏  举报