Struts2自定义返回Json类型result
本来Struts2有自己的json类型的返回结果,并提供了插件,但是它有一个问题,那就是它会将所有序列化的字段都返回,如果想要制定返回Action的某一个属性,则需要在配置result时,配置参数(这里只是举个例子):
<param name="root">responseMap</param>
配置了这个参数,返回结果就会从Action中的responseMap为根进行返回。
但是如果自定义结果类型,就可以自己控制了,而且不需要struts2-json-result插件,以下是配置信息:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.objectFactory" value="spring" />
<constant name="struts.i18n.encoding" value="utf-8" />
<constant name="struts.enable.SlashesInActionNames" value="true" />
<package name="default" extends="struts-default" namespace="/login">
<result-types>
<result-type name="jsonResult" class="com.lxl.student.mng.base.JSONResult" />
</result-types> <action name="*/*" class="{1}" method="{2}">
<result type="jsonResult" name="success">
<param name="resultName">responseData</param>
</result>
</action>
</package> </struts>
com.lxl.erp.base.JSONResult为我们自己需要实现的返回类型的实现类:
package com.lxl.student.mng.base; import java.io.PrintWriter;
import java.lang.reflect.UndeclaredThrowableException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.StrutsResultSupport; import com.lxl.student.mng.common.HttpConstant;
import com.lxl.student.mng.common.ResourceLanguage;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.ExceptionHolder;
import com.opensymphony.xwork2.util.ValueStack; import net.sf.json.JSONObject; public final class JSONResult extends StrutsResultSupport {
private static final long serialVersionUID = 1L; private String resultName; public void setResultName(String resultName) {
this.resultName = resultName;
} @Override
protected void doExecute(String finalLocation, ActionInvocation invocation) throws Exception {
BaseAction bas = (BaseAction) invocation.getAction();
bas.clearErrorsAndMessages(); HttpServletResponse response = (HttpServletResponse) invocation.getInvocationContext().get(HTTP_RESPONSE);
response.setContentType(HttpConstant.RESPONSE_CONTENT_TYPE); @SuppressWarnings("unchecked")
Map<String, Object> responseMap = (Map<String, Object>) invocation.getStack().findValue(resultName); if (responseMap == null) {
responseMap = new HashMap<String, Object>(3);
} else if (responseMap.get(HttpConstant.RETCODE) == null) {
ValueStack s = invocation.getStack();
for (int i = s.size(); i > 0; i--) {
Object obj = s.pop();
if (obj instanceof ExceptionHolder) {
responseMap.put(HttpConstant.RETCODE, HttpConstant.ERROR_CODE);
responseMap.put(HttpConstant.RETMSG, HttpConstant.UNKNOWNERROR); Object o = ((ExceptionHolder) obj).getException(); if (o instanceof ServiceException) {
String accept_language = ServletActionContext.getRequest()
.getHeader(HttpConstant.REQUEST_HEADER_LANG);
String language = accept_language.split(",")[0];
Locale locale = Locale.getDefault();
if (language.toLowerCase().indexOf(ResourceLanguage.CHINESE) > -1) {
locale = Locale.CHINA;
} else if (language.toLowerCase().indexOf(ResourceLanguage.ENGLISH) > -1) {
locale = Locale.US;
}
ResourceBundle bundle = ResourceBundle.getBundle(ResourceLanguage.SOURCELOCATION, locale); ServiceException exception = (ServiceException) o; responseMap.put(HttpConstant.RETMSG, exception.getErrorMsg(bundle));
} else if (o instanceof Exception) {
Exception exception = (Exception) o;
responseMap.put(HttpConstant.RETMSG, exception.getCause().getMessage());
} else if (o instanceof UndeclaredThrowableException) {
o = ((UndeclaredThrowableException) o).getUndeclaredThrowable();
}
break;
}
}
} PrintWriter pw = response.getWriter();
pw.write(JSONObject.fromObject(responseMap).toString()); System.out.println(JSONObject.fromObject(responseMap)); return;
}
}
这样,只要在Action中添加一个属性responseMap存储要返回的数据,通过
(Map<String, Object>) invocation.getStack().findValue(resultName)
在值栈中获取返回的数据(resultName是在struts.xml中配置的,struts会将值压入到值栈中,通过这个配置的名字就可以找到)。
这样Action请求处理函数中,将要返回的请求数据结果放到responseMap中,然后返回SUCCESS就可以了,前台就可以通过ajax请求访问了。
注:
HttpConstant.RESPONSE_CONTENT_TYPE="text/plain; charset=UTF-8"
Struts2自定义返回Json类型result的更多相关文章
- Struts2+Jquery实现ajax并返回json类型数据
来源于:http://my.oschina.net/simpleton/blog/139212 摘要 主要实现步骤如下: 1.JSP页面使用脚本代码执行ajax请求 2.Action中查询出需要返回的 ...
- 转载:Struts2+Jquery实现ajax并返回json类型数据
摘要: 主要实现步骤如下: 1.JSP页面使用脚本代码执行ajax请求 2.Action中查询出需要返回的数据,并转换为json类型模式数据 3.配置struts.xml文件 4.页面脚本接受并处理数 ...
- 3.自定义返回json格式的数据给前台(自定义Controller类中的Json方法)
在mvc的项目中,我们前台做一些操作时,后台要返回一些结果给前台,这个时候我们就需要有一个状态来标识到底是什么类型的错误, 例如: 执行删除的时候,如果操作成功(1行受影响),我们需要返回状态为1并输 ...
- struts2 ajax jquery返回json类型
三个页面, <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC & ...
- Extjs 4.1 struts2.3 返回json 初试
之前曾经使用过3.x版本的extjs,当时可以结合struts实现各种基本的增删查改.但是4.1版本中增加了一些属性,出现了一些新的使用方法,导致错误不断,有的时候调用到相应的action却返回不了值 ...
- struts2注解返回json
Struts2使用注解方式返回Json数据 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/Geek_Alex/article/details/788 ...
- SpringMvc返回JSON出现"$.result.currentLevel"
"$.result.currentLevel" 问题描述 使用SpringMvc返回一个json数据的时候,会在产生的结果中出现如下的问题:"$.result.curre ...
- struts2后台返回json到jsp页面
1.在action定义一个全局变量如: private Map<String, Object> dataMap; 2.控制层方法 说明:主要的目的是把我们定义的Map转为Json对象,然后 ...
- Spring boot返回JSON类型响应及Content-Type设置
一.背景 服务器软件用Spring boot开发,API调用的响应消息格式为JSON. 对端调用接口后无法解析响应. 抓包看Response的Body部分确实是正确的JSON格式字符串. 二.问题分析 ...
随机推荐
- SA模板
#include<cstdio> #include<algorithm> #include<cstring> using namespace std; ; char ...
- “亚信科技杯”南邮第七届大学生程序设计竞赛之网络预赛 A noj 2073 FFF [ 二分图最大权匹配 || 最大费用最大流 ]
传送门 FFF 时间限制(普通/Java) : 1000 MS/ 3000 MS 运行内存限制 : 65536 KByte总提交 : 145 测试通过 : 13 ...
- msp430入门编程36
msp430中C语言的可移植--面向接口实现
- MITM Proxy环境搭建
MITM_Proxy环境搭建 环境要求 系统环境要求: Ubuntu 14.04 x64,CentOS 7 x64以上版本系统(建议使用xubuntu 14.04 x64,稳定硬件要求低) Pytho ...
- Flex的Combobox组件使用技巧
1.显示提示设置Prompt属性可以为Combobox添加一个默认提示.如果没有设置selectedIndex,默认selectedIndex=-1,就显示Prompt的内容.Flex3如果不设置Pr ...
- springboot使用过程中遇到的问题
一.工具Intellij IDEA 二.基本问题 1.数据库语句 Caused by: java.lang.IllegalStateException: Cannot load driver clas ...
- Spring Boot应用的启动和停止(Spring Boot应用通过start命令启动)
Spring Boot,作为Spring框架对“约定优先于配置(Convention Over Configuration)”理念的最佳实践的产物,它能帮助我们很快捷的创建出独立运行.产品级别的基于S ...
- guava缓存设置return null一直报错空指针
guava缓存设置return null一直报错空指针 因为缓存不允许返回为空
- CentOS 7.0安装Zimbra 8.6邮件服务器
Zimbra的核心产品是Zimbra协作套件(Zimbra Collaboration Suite,简称ZCS). 系统:Centos7 ip地址:192.168.127.131 安装前准备 1.关闭 ...
- Angular2.x-主/细节组件
此刻,HeroesComponent显示heroes列表和所选heroes的详细信息. 随着应用程序的增长保持一个组件中的所有功能将不可维护.您需要将大型组件分成更小的子组件,每个组件都专注于特定的任 ...