用例需要依赖的jar:

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

Struts2AjaxAction.java

 package test.action.ajax;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import test.util.BaseAction; @ParentPackage("ajax")
@Namespace("/test")
public class Struts2AjaxAction extends BaseAction
{
/**
* struts2-ajax 用例
*/
private static final long serialVersionUID = -4227395311084215139L; @Action(value = "gotoStruts2JsonPlugin", results = {
@Result(name = "success", location = "/WEB-INF/content/test/ajax/struts2JsonPlugin.jsp")})
public String gotoStruts2JsonPlugin()
{
return SUCCESS;
} @Action(value = "gotoStruts2Ajax_post", results = {
@Result(name = "success", location = "/WEB-INF/content/test/ajax/struts2Ajax_post.jsp")})
public String struts2Ajax_post()
{
return SUCCESS;
} @Action(value = "gotoStruts2Ajax_ajax", results = {
@Result(name = "success", location = "/WEB-INF/content/test/ajax/struts2Ajax_ajax.jsp")})
public String struts2Ajax_ajax()
{
return SUCCESS;
} @Action(value = "post")
public String post()
{
String f1 = StringUtils.defaultString(getRequest().getParameter("field1"));
String f2 = StringUtils.defaultString(getRequest().getParameter("field2"));
ajaxText(f1+",测试,"+f2);
return null;
} @Action(value = "ajax")
public String ajax() throws UnsupportedEncodingException
{
String f1 = StringUtils.defaultString(getRequest().getParameter("field1"));
String f2 = StringUtils.defaultString(getRequest().getParameter("field2")); Map<String, String> jsonMap = new HashMap<String, String>();
jsonMap.put(f1, f1);
jsonMap.put(f2, f2);
jsonMap.put("status", SUCCESS);
super.ajaxJson(jsonMap);
return null;
}
}
  • 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

 <%@ 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>使用$.post提交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 post()
{
// 以form1表单封装的请求参数发送请求。
$.post('${cxtpath}/test/post.action', $("#form1").serializeArray(),
// data代表服务器响应,此处只是把服务器响应显示出来
function(data) {
console.log("data:"+JSON.stringify(data));
}
)
}
</script>
</head>
<body>
<div>使用$.post提交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="post();"/></td>
</tr>
</s:form>
</div>
</body>
</html>

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

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

struts2,实现Ajax异步通信的更多相关文章

  1. Struts2与Ajax的整合

    整合: 导入jar包 sturts2-json-plugin-2.1.8.1.jar 说明: 在该jar包中有struts-plugin.xml文件 <struts>            ...

  2. Struts2之ajax初析

    Web2.0的随波逐流,Ajax那是大放异彩,Struts2框架自己整合了对Ajax的原生支持(struts 2.1.7+,之前的版本可以通过插件实现),框架的整合只是使得JSON的创建变得异常简单, ...

  3. Struts2与ajax整合之缺点

    之前有篇博客介绍了Struts2与ajax的整合,链接Struts2之-集成Json插件实现Ajax 这里不再累述,看以上博客. 此篇博客想吐槽一下Struts2的缺点--错误处理做的不好,怎么做的不 ...

  4. Struts2结合Ajax实现登录

    前言:Struts2作为一款优秀的MVC框架,和Ajax结合在一起,用户就会有良好的体验,本篇博文我们来模拟一个简单的登录操作,实现Ajax的异步请求,其中Struts2进行的是链接处理,Action ...

  5. Struts2 利用AJAX 导出大数据设置遮罩层

    Struts2 利用AJAX 导出大数据设置遮罩层 需求背景: 每次我们导出excel的时候 ,如果数据量很大,导出花费的时间会很长,页面却有没人任何反应,这个时候用户会认为系统有问题,要么关了页面, ...

  6. Struts2对AJAX的支持

    一.简介        struts2确实一个非常棒的MVC框架.这里部分记述一下struts2对AJAX的支持.实现AJAX有两种方式,一种是使用原生的javascript代码实现,一种是使用第三方 ...

  7. 本机Ajax异步通信

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

  8. Struts2 处理AJAX请求

    Struts2整合AJAX有2种方式: 使用type="stream"类型的<result> 使用JSON插件 使用type="stream"类型的 ...

  9. Struts2实现ajax的两种方式

    基于Struts2框架下实现Ajax有两种方式,第一种是原声的方式,另外一种是struts2自带的一个插件. js部分调用方式是一样的: JS代码: function testAjax() { var ...

随机推荐

  1. Ubuntu下virtualbox nat网络模式下 实现宿主机访问虚拟机

    参考原文(在windows环境下):http://hi.baidu.com/george_gly/item/5183b76e5a79e49ac5d2498b nat网络模式下,虚拟机可以访问外网.访问 ...

  2. 通过sqlserver日志恢复误删除的数据

     如果你已经急的焦头烂额,看到这篇文章的时候,请你换个坐姿,深呼吸几次,静下心来将这篇文章读完,也许你的问题迎刃而解. 我遇到的情况是这样的,网站被植入木马,盗取了我的web.config文件,web ...

  3. iPhone批量删除照片/视频最好用的方法

    iPhone批量删除照片/视频最好用的方法 经过大量的搜索和不懈的尝试,今天终于找到了批量删除iPhone照片最好用的方法, 于是决定写一篇博客为更多的果粉们造福! 1. 通过USB将iPhone手机 ...

  4. MvvmLight 绑定

    添加MvvmLight引用,通过Nuget: 加载nuget以后会有ViewModelLocator.cs: 新建自己的ViewModel,继承ViewModelBase: View 通过资源引用Vi ...

  5. Vue.2.0.5-深入响应式原理

    大部分的基础内容我们已经讲到了,现在讲点底层内容.Vue 最显著的一个功能是响应系统 -- 模型只是普通对象,修改它则更新视图.这会让状态管理变得非常简单且直观,不过理解它的原理以避免一些常见的陷阱也 ...

  6. C# 匿名方法

    每次写博客,第一句话都是这样的:程序员很苦逼,除了会写程序,还得会写博客!当然,希望将来的一天,某位老板看到此博客,给你的程序员职工加点薪资吧!因为程序员的世界除了苦逼就是沉默.我眼中的程序员大多都不 ...

  7. linux_x86_64 blat安装

    blatSrc35.zip下载地址:http://users.soe.ucsc.edu/~kent/src/ 对于下载好的源代码安装包blatSrc35.zip,需进行编译,安装过程如下: 1.用un ...

  8. eclipse 导入jdbc4.jar 包

    详细讲解链接 http://wenku.baidu.com/link?url=QUhO2rIL2fYRgOUyd1TQPEgbl0jQr156ioxK5fiwSPm_Tset2okpBEJcO1fmz ...

  9. android中的权限(转)

    Android权限系统非常庞大,我们在Android系统中做任何操作都需要首先获取Android系统权限,本文记录了所有的Android权限问题,整理一下分享给大家. 访问登记属性 android.p ...

  10. nginx的基本配置和虚拟主机的配置

    在Nginx配置文件(nginx.conf)中,一个最简化的虚拟主机配置代码如下: 跟Apache -样,Nginx也可以配置多种类型的虚拟圭机:一是基于IP的虚拟主机,二是基于域名的虚拟主机,三是基 ...