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 下午 ...
随机推荐
- 建字段_添加数据_生成json.php
<?php header("Content-Type:text/html;charset=utf8"); class db{ static $localhost = &quo ...
- Android百度地图开发(一)之初体验
转载请注明出处:http://blog.csdn.net/crazy1235/article/details/42614603 做关于位置或者定位的app的时候免不了使用地图功能,本人最近由于项目的需 ...
- MongoDB是?
MongoDB是? MongoDB是一个基于分布式文件存储的数据库 由C++编写 旨在为 WEB 应用提供可扩展的高性能数据存储解决方案 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当 ...
- passport 自动取密码
django settings.py """ Django settings for password project. Generated by . For more ...
- oracle启动关闭命令
关闭:1.shutdown normal 不允许新的连接.等待会话结束.等待事务结束.做一个检查点并关闭数据文件.启动时不需要实例恢复. 2.shutdown transactional不允许新的连接 ...
- Xib文件的使用
- The Struts dispatcher cannot be found. This is usually caused by using Strut
The Struts dispatcher cannot be found. This is usually caused by using Struts tags without the assoc ...
- VVDocumenter 注释工具的使用
首先,前往github上下载工程源代码. 然后,编译VVDocumenter工程. 重启xcode. 然后,只要在你自己的工程中要加入注释的方法前面输入“///”,一切搞定. 很好很强大.
- node.js npm权限问题try running this command again as root/Administrator.
npm install报错; try running this command again as root/Administrator. 以管理员身份打开cmd 开始菜单->所有程序->附 ...
- 删除NSMutableArray中的二维数组
// 删除模型数据 [self.mutableArr[indexPath.section] removeObjectAtIndex:indexPath.row]; //删除UI(刷新数据,UI) [s ...