用例需要依赖的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

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

转载于:https://www.cnblogs.com/xiluhua/p/4390046.html

struts2,实现Ajax异步通信相关推荐

  1. 本机Ajax异步通信

    昨天我们用JQuery.Ajax解释JQuery样通过Ajax实现异步通信.为了更好的编织知识网,今天我们用一个Demo演示怎样用javascript实现原生Ajax的异步通信. 原生Ajax实现异步 ...

  2. java ajax报错500,(Struts2+JSON+Ajax) XMLHttpRequest ==500如何解决

    (Struts2+JSON+Ajax) XMLHttpRequest ==500怎么解决? 本帖最后由 zjlisok 于 2013-01-29 02:00:05 编辑 XMLHttpRequest. ...

  3. Struts2之ajax初析

    2019独角兽企业重金招聘Python工程师标准>>> Web2.0的随波逐流,Ajax那是大放异彩,Struts2框架自己整合了对Ajax的原生支持(struts 2.1.7+,之 ...

  4. struts2 ajax html,Struts2+Jquery+Ajax+Json

    现在使用Json来封装并且传递数据的情形是越来越多了,可怎么样在Struts2中来使用Jquery+Ajax+Json来协同工作呢?在网上查了下就那几个例子被转过来转过去的,还有很多例子根本行不通,这 ...

  5. struts2+jquery+ajax实现上传校验实例

    一直以为ajax不能做上传,直到最近看了一些文章.需要引入AjaxFileUploaderV2.1.zip,下载链接:http://pan.baidu.com/s/1i3L7I2T 代码和相关配置如下 ...

  6. struts2、ajax实现前后端交互

    跳过struts2环境搭建部分,或者可以看我的博客(http://www.cnblogs.com/zhangky/p/8436472.html),里面有写,很详细. 需要导入的jar包(struts官 ...

  7. php 与结合struts2,Struts2和Ajax数据交互示例详解

    前言 我们从Web 2.0的随波逐流,Ajax的大放异彩说起,Struts2框架自己整合了对Ajax的原生支持(struts 2.1.7+,之前的版本可以通过插件实现),框架的整合只是使得JSON的创 ...

  8. struts2 jquery ajax 局部刷新遇到的各种问题

    我们的网站一开始都是由前台提交表单到action,每次一个小操作整个页面都会刷新,影响用户体验,这次由我实现部分功能的局部刷新,但是初学ajax遇到不少问题 1.我们在struts.xml外扩展了一个 ...

  9. Jquery实现AJAX异步通信

    目录 Ajax的简介 Ajax的特点 Ajax向后端发送请求 发送请求后端数据回显 Ajax的简介 Ajax(Asynchronous JavaScript and XML),直译为"异步的 ...

最新文章

  1. linux系统调用理解之摘录(3)
  2. 微信看一看实时相关推荐介绍
  3. oracle的隐式游标有哪些,Oracle隐式游标小例子
  4. 在Asp.net core 项目中操作Mysql数据库
  5. 万能无线键盘对码软件_Ceke M87蓝牙机械键盘拆解评测 - Mac小伴侣
  6. 如何在Global.asax中判断是否是ajax请求
  7. Hihocoder 1632 : Secret Poems 思维|技巧
  8. server sql 众数_sql 语句系列(众数中位数与百分比)[八百章之第十五章]
  9. java.lang.UnsatisfiedLinkError: D:\Program Files\apache-tomcat-9.0.30\bin
  10. 在php中isset什么意思,php – isset()和__isset()之间有什么区别?
  11. servlet和jsp的转发与重定向代码以及区别
  12. cad道路里程桩号标注_【收藏】甲级设计院全专业CAD制图标准
  13. 数据来看吃热狗王校长的微博究竟有多火!
  14. 从DLL导出LIB文件
  15. AHP(层次分析法)的全面讲解及python实现
  16. 三维交互电子沙盘在消防应急指挥部的一张图建立方案
  17. JavaScript中的数组方法总结+详解
  18. Can‘t find bundle for base name jdbc, locale zh_CN的解决方法
  19. php如何调用protected,PHP中类作用域protected实例详解
  20. 关于pdms中设备参数模板的更新PML代码

热门文章

  1. 铺铜过孔不要十字_谈谈商周青铜器上圈足的镂孔现象
  2. 汇编 cmp_汇编复习
  3. LeetCode 03. 无重复字符的最长子串
  4. java中逗号怎么加_Java中如何将字符串从右至左每三位加一逗号
  5. python中带附件发送电子邮件_python发送带附件邮件
  6. android 多个复选框,Android UI控件之CheckBox(复选框、多选框)
  7. 【渝粤教育】国家开放大学2019年春季 1018国际公法 参考试题
  8. [渝粤教育] 西南科技大学 复习资料 法理学
  9. 【渝粤题库】国家开放大学2021春2626药事管理与法规题目
  10. android交互功能,Android 用户界面交互---拖放(OnDragListener)