用例需要依赖的jar:

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

struts2-json-plugin插件实现异步通信的更多相关文章

  1. 火狐谷歌浏览器Json查看插件

    1.搜: Firefox的JSON插件 参考: Chrome/FireFox浏览器下处理JSON的插件_Bruce_新浪博客 JSONView :: Firefox 附加组件 但是后来去发现没用: 打 ...

  2. Android+struts2+JSON方式的手机开发(Login)

    在手机的后台服务无论是调用WebService还是Http请求,多数都是采用Android的HttpClient实现相关的调用实现.本文实现Android+Struts2+JSON方式实现为手机前台提 ...

  3. struts2 json 定义全局Date格式

    使用struts2的json插件时,自己定义日期格式经常使用的方式是在get属性上加入@JSON注解,这个对于少量Date属性还能够,可是假设date字段多了,总不可能去给每一个date get方法加 ...

  4. Class org.apache.struts2.json.JSONWriter can not access a member of class oracle.jdbc.driver.Physica

    产生这个错误的原因是因为我的oracle数据库中有一个CLOB字段,查询出来的时候要转换为JSON而报错. Class org.apache.struts2.json.JSONWriter can n ...

  5. struts2 json 输出日期格式不正确

    struts2 输出json中 日期出现:2013-12-17T15:57:47 错误格式的数据 原因:struts2 json插件对日期的格式化有问题 解决方法:在实体类的日期的get方法上加注解: ...

  6. webpack(9)plugin插件功能的使用

    plugin 插件是 webpack 的支柱功能.webpack 自身也是构建于你在 webpack 配置中用到的相同的插件系统之上! 插件目的在于解决 loader 无法实现的其他事. 常用的插件 ...

  7. Jenkins 安装的HTML Publisher Plugin 插件无法展示ant生成的JunitReport报告

    最近在做基于jenkins ant  junit 的测试持续集成,单独ant junit生成的junitreport报告打开正常,使用Jenkins的HTML Publisher Plugin 插件无 ...

  8. yformater - chrome谷歌浏览器json格式化json高亮json解析插件

    yformater是一款chrome浏览器插件,用来格式化(高亮)服务端接口返回的json数据. 实际上小菜并不是第一个写这种插件的,但是现有的chrome json格式化插件实在是不太好用,索性小菜 ...

  9. struts2 java.lang.StackOverflowError org.apache.struts2.json.JSONWriter

    1. 问题描述: 页面通过异步访问action,    action的方法通过map封装数据,struts的result的type设置为json,后台报错 六月 25, 2016 6:54:33 下午 ...

随机推荐

  1. Java代码中执行Linux命令,亲测可用

    前提需要知道怎么在linux怎么新建java文件和怎么编译,否则请先学其他知识!! import java.io.*;public class Test{ public static void mai ...

  2. HtmlAgilityPack教程

    解析html教程(重点) http://www.cnblogs.com/kissdodog/archive/2013/02/28/2936950.html 完整的教程 http://www.cnblo ...

  3. MIConvexHull

    http://miconvexhull.codeplex.com/ 可以生成2.3维的最小凸包.可以进行狄洛尼三角剖分,生成Voronoi多边形. This project is a convex h ...

  4. cocos2dx 3.x(捕鱼达人炮台角度换算)

    // // GameScence.hpp // NotesDamo // // Created by apple on 16/10/23. // // #ifndef GameScence_hpp # ...

  5. oracle开启numa的支持

    在11.2中,即使是系统支持numa架构,oracle默认也不再检测硬件是否支持numa,也不开启对numa的支持. 要想开启对numa的支持,必须设置隐含参数: _enable_NUMA_suppo ...

  6. OSPF理解

    from http://kingdee.blog.51cto.com/98119/27310STP,PIM,OSPF,长的好像(*_*)可以把整个网络(一个自治系统AS)看成一个王国,这个王国可以分成 ...

  7. mapreduce小结

    (不断更新) MapReduce架构是一种分布式编程架构,它本质上是将任务划分,然后归并.它是以数据为中心的编程架构,相比与分布式计算和并行计算等,它更看重的是吞吐率.它处理的数据是PB级的数据,它并 ...

  8. SQL Server 2008中的Service SID 介绍

    [介绍] 我们打开SQL Server 2008 Management Studio, 会发现有如下几个登录: NT SERVICE\ClusSvc, NT SERVICE\MSSQL$KATMAI和 ...

  9. Spring shiro使用

    maven依赖: <dependency> <groupId>commons-collections</groupId> <artifactId>com ...

  10. 多语言本地化开发Localized

    NSString * ViewsLocalizedStringFormat(NSString *key,NSString *defValue); // Handle localized strings ...