struts2-json-plugin插件实现异步通信
用例需要依赖的jar:
- struts2-core.jar
- struts2-convention-plugin.jar,非必须,
- struts2-json-plugin.jar
- 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插件实现异步通信的更多相关文章
- 火狐谷歌浏览器Json查看插件
1.搜: Firefox的JSON插件 参考: Chrome/FireFox浏览器下处理JSON的插件_Bruce_新浪博客 JSONView :: Firefox 附加组件 但是后来去发现没用: 打 ...
- Android+struts2+JSON方式的手机开发(Login)
在手机的后台服务无论是调用WebService还是Http请求,多数都是采用Android的HttpClient实现相关的调用实现.本文实现Android+Struts2+JSON方式实现为手机前台提 ...
- struts2 json 定义全局Date格式
使用struts2的json插件时,自己定义日期格式经常使用的方式是在get属性上加入@JSON注解,这个对于少量Date属性还能够,可是假设date字段多了,总不可能去给每一个date get方法加 ...
- 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 ...
- struts2 json 输出日期格式不正确
struts2 输出json中 日期出现:2013-12-17T15:57:47 错误格式的数据 原因:struts2 json插件对日期的格式化有问题 解决方法:在实体类的日期的get方法上加注解: ...
- webpack(9)plugin插件功能的使用
plugin 插件是 webpack 的支柱功能.webpack 自身也是构建于你在 webpack 配置中用到的相同的插件系统之上! 插件目的在于解决 loader 无法实现的其他事. 常用的插件 ...
- Jenkins 安装的HTML Publisher Plugin 插件无法展示ant生成的JunitReport报告
最近在做基于jenkins ant junit 的测试持续集成,单独ant junit生成的junitreport报告打开正常,使用Jenkins的HTML Publisher Plugin 插件无 ...
- yformater - chrome谷歌浏览器json格式化json高亮json解析插件
yformater是一款chrome浏览器插件,用来格式化(高亮)服务端接口返回的json数据. 实际上小菜并不是第一个写这种插件的,但是现有的chrome json格式化插件实在是不太好用,索性小菜 ...
- struts2 java.lang.StackOverflowError org.apache.struts2.json.JSONWriter
1. 问题描述: 页面通过异步访问action, action的方法通过map封装数据,struts的result的type设置为json,后台报错 六月 25, 2016 6:54:33 下午 ...
随机推荐
- H3C交换机配置
h3c 交换机的配置命令 通过 console 连接到交换机 交换机所使用的 console 接口看上去像是一个普通的 RJ45 网卡接口,但是并不能使用普通的网线与 PC 连接 ^_^ .它要通过 ...
- 第二篇 Replication:分发服务器的作用
本篇文章是SQL Server Replication系列的第二篇,详细内容请参考原文. 分发服务器是SQL Server复制的核心组件.分发服务器控制并执行数据从一个服务器移动到另一个服务器的进程. ...
- 误卸载python2.4导致yum不能用后的修复
去 http://mirrors.ustc.edu.cn/centos/或者镜像下载如下包,版本不一定非常一致 python-2.4.3-56.el5.x86_64.rpmpython-devel-2 ...
- CPU boot up过程
1. CPU0 BOOT CPU1 BOOT 通过IPC互相通信 2. CPU1 BOOT 完后,loop,等待IPC from CPU0 3. cpu0 写IPC通知CPU1,cpu1 ...
- SpinLock 实现
/* Example: SpinLock Description: SpinLock is the lock implementation using AtomicInteger as a primi ...
- Python和Ruby开发中源文件中文注释乱码的解决方法(Eclipse和Aptana Studio3均适用)
Eclipse的设置(Aptana Studio3与Eclipse基本完全相同,此处略) window->preferences->general->editors->text ...
- MyEclipse 下 Tomcat启动变慢如何解决
MyEclipse 下 Tomcat启动变慢如何解决 项目使用debug启动有时候会突然变得非常慢.不但启动慢,启动之后连打开项目页面也很慢,是日常的4,5倍.可以有下面的几种解决方法: 1. ...
- C makefile
Makefile编写 hello.out:max.o main.c gcc max.o main.c -o hello.out max.o:max.c gcc -c max.c -o max.o
- linux时间的查看与修改
1.查看时间和日期 date 2.设置时间和日期 将系统日期设定成1996年6月10日的命令 date -s 06/22/96 将系统时间设定成下午1点52分0秒的命令 date -s 13:52:0 ...
- paper 50 :人脸识别简史与近期进展
自动人脸识别的经典流程分为三个步骤:人脸检测.面部特征点定位(又称Face Alignment人脸对齐).特征提取与分类器设计.一般而言,狭义的人脸识别指的是"特征提取+分类器"两 ...