SpringMVC已经大行其道。一般的,都是返回JSP视图。如果需要返回JSON格式,我们大都掌握了一些方法。

  在ContentNegotiatingViewResolver之前,一般使用XmlViewResolver的location属性,手工编写一个视图专门处理Json类型,就是将返回的数据封装成Json输出。下面介绍该方案具体代码。

  exam-servlet.xml:

    <bean id="xmlViewResolver" class="org.springframework.web.servlet.view.XmlViewResolver">
<property name="order" value="1"/>
<property name="location" value="/WEB-INF/views.xml"/>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="order" value="2"></property>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
</bean>

  views.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="json" class="cc.monggo.web.views.JsonView"></bean>
</beans>

  JsonView.java

/**
*
*/
package cc.monggo.web.views; import java.util.HashMap;
import java.util.Iterator;
import java.util.Map; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;
import net.sf.json.filters.OrPropertyFilter;
import net.sf.json.util.PropertyFilter; import org.springframework.web.servlet.view.AbstractView; import cc.monggo.web.form.BaseForm; /**
* @author fangjinsong
*
*/
public class JsonView extends AbstractView {
private static final String DEFAULT_JSON_CONTENT_TYPE = "application/json;charset=UTF-8";
private boolean forceTopLevelArray = false;
private boolean skipBindingResult = true;
private JsonConfig jsonConfig = new JsonConfig(); public JsonView() {
super();
setContentType(DEFAULT_JSON_CONTENT_TYPE);
} public boolean isForceTopLevelArray() {
return forceTopLevelArray;
} public void setForceTopLevelArray(boolean forceTopLevelArray) {
this.forceTopLevelArray = forceTopLevelArray;
} public boolean isSkipBindingResult() {
return skipBindingResult;
} public void setSkipBindingResult(boolean skipBindingResult) {
this.skipBindingResult = skipBindingResult;
} public JsonConfig getJsonConfig() {
return jsonConfig;
} public void setJsonConfig(JsonConfig jsonConfig) {
this.jsonConfig = jsonConfig != null ? jsonConfig : new JsonConfig();
if (skipBindingResult) {
PropertyFilter jsonPropertyFilter = this.jsonConfig.getJavaPropertyFilter();
if (jsonPropertyFilter == null) {
this.jsonConfig.setJsonPropertyFilter(new BindingResultPropertyFilter());
} else {
this.jsonConfig.setJsonPropertyFilter(new OrPropertyFilter(new BindingResultPropertyFilter(), jsonPropertyFilter));
}
}
} public static String getDefaultJsonContentType() {
return DEFAULT_JSON_CONTENT_TYPE;
} public boolean isIgnoreDefaultExcludes() {
return getJsonConfig().isIgnoreDefaultExcludes();
} public void setExcludedProperties(String[] excludedProperties) {
jsonConfig.setExcludes(excludedProperties);
} public void setIgnoreDefaultExcludes(boolean ignoreDefaultExcludes) {
jsonConfig.setIgnoreDefaultExcludes(ignoreDefaultExcludes);
} protected String[] getExcludedProperties() {
return jsonConfig.getExcludes();
} @Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setContentType(getContentType());
Map newModel = new HashMap();
for (Iterator it = model.keySet().iterator(); it.hasNext();) {
Object key = it.next();
Object value = model.get(key);
if (!(value instanceof BaseForm)) {
newModel.put(key, value);
}
}
writeJSON(newModel, request, response);
} protected void writeJSON(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
JSON json = createJSON(model, request, response);
if (forceTopLevelArray) {
json = new JSONArray().element(json);
}
json.write(response.getWriter());
} protected final JSON defaultCreateJSON(Map model) {
if (skipBindingResult && jsonConfig.getJavaPropertyFilter() == null) {
jsonConfig.setJsonPropertyFilter(new BindingResultPropertyFilter());
}
return JSONSerializer.toJSON(model, jsonConfig);
} private JSON createJSON(Map model, HttpServletRequest request, HttpServletResponse response) {
return defaultCreateJSON(model);
} private static class BindingResultPropertyFilter implements PropertyFilter {
@Override
public boolean apply(Object source, String name, Object value) {
return name.startsWith("org.springframework.validation.BindingResult");
}
} }

  这种方案会增加一个views.xml文件。另一个方案使用ContentNegotiatingViewResolver内容协商解析器。该解析器可以解析多种Controller返回结果,方法是分派给其他的解析器解析。这样就可以返回JSP视图,Xml视图,Json视图。其中Json视图由MappingJacksonJsonView视图表示。ContentNegotiatingViewResolver的一般配置如下:

    <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1" />
<property name="ignoreAcceptHeader" value="true" />
<property name="favorParameter" value="false" />
<property name="defaultContentType" value="text/html" />
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
</map>
</property>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp"></property>
</bean>
</list>
</property>
<property name="defaultViews">
<list>
<bean id="json" class="com.mogee.web.views.MogeeMappingJacksonJsonView" />
</list>
</property>
</bean>

  要返回Json格式数据,Controller中一般使用JsonResult,@responseBody等技术。例如:

@RequestMapping("/json3.json")
public JsonResult testJson3(@RequestBody User u){
log.info("handle json output from ContentNegotiatingViewResolver");
return new JsonResult(true,"return ok");
}

  这样一来,有一个问题:Controller总是返回Object对象,不能返回ModelAndview类型。按笔者的经验,经常有这样的需求:一个请求,如果返回了正确的结果,返回正常的JSP;如果返回了错误的结果,我们希望返回Json类型数据。为了满足这样要求,一般使用response.getWriter.print("")技术。笔者并不喜欢这样写法,不像Spring的风格。所以下面笔者将提出第二种方案。两者都能兼顾。Contoller代码如下。

@RequestMapping(value = "/test", method = RequestMethod.GET)
public ModelAndView jsonView(HttpServletRequest request, HttpServletResponse response, HelloForm form)
throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
map.put("hello", "Hello");
ModelAndView mv = new ModelAndView(new MappingJacksonJsonView(), map);
return mv;
}

  通过这样的代码,可以在Controller中灵活控制,返回JSON或者JSP都可以。看似完美的方案,也有一个问题,返回的时候会将Form也打包到Json中去。如下:

  原因是因为MappingJacksonJsonView代码中将数据map,mv.add(),还有form,还有错误提示等四项数据都加入Json,原程序只是过滤了错误提示,所以就留下了form数据。

为此我们需要重写MappingJacksonJsonView,将剩余三种数据中的form也过滤掉。一般的,form都会继承BaseForm,所以只要使用instanceof判断即可。这样的改造简洁明了,符合Spring编程的特点。具体代码如下:

public class MogeeMappingJacksonJsonView extends MappingJacksonJsonView {
@Override
protected Object filterModel(Map<String, Object> model) {
Map<String, Object> result = new HashMap<String, Object>(model.size());
Set<String> renderedAttributes = !CollectionUtils.isEmpty(super.getRenderedAttributes()) ? super
.getRenderedAttributes() : model.keySet();
for (Map.Entry<String, Object> entry : model.entrySet()) {
if (!(entry.getValue() instanceof BindingResult) && renderedAttributes.contains(entry.getKey())) {
if (!(entry.getValue() instanceof BaseForm)) {
result.put(entry.getKey(), entry.getValue());
}
}
}
return result;
}
}

相应的,exam-servlet.xml中也要修改,代码如下:

如此,就完成了输出Json的方案。

                                                      方劲松 东莞虎门信丰物流

                                                        2015.3.20

SpringMVC返回JSON方案的更多相关文章

  1. 【Spring学习笔记-MVC-3.1】SpringMVC返回Json数据-方式1-扩展

    <Spring学习笔记-MVC>系列文章,讲解返回json数据的文章共有3篇,分别为: [Spring学习笔记-MVC-3]SpringMVC返回Json数据-方式1:http://www ...

  2. 【Spring学习笔记-MVC-4】SpringMVC返回Json数据-方式2

    <Spring学习笔记-MVC>系列文章,讲解返回json数据的文章共有3篇,分别为: [Spring学习笔记-MVC-3]SpringMVC返回Json数据-方式1:http://www ...

  3. 【Spring学习笔记-MVC-3】SpringMVC返回Json数据-方式1

    <Spring学习笔记-MVC>系列文章,讲解返回json数据的文章共有3篇,分别为: [Spring学习笔记-MVC-3]SpringMVC返回Json数据-方式1:http://www ...

  4. SpringMVC返回Json,自定义Json中Date类型格式

    http://www.cnblogs.com/jsczljh/p/3654636.html —————————————————————————————————————————————————————— ...

  5. 配置SpringMVC返回JSON遇到的坑

    坑一:官方网站下载地址不明朗,最后找了几个下载地址:http://wiki.fasterxml.com/JacksonDownload Jackson2.5下载地址:jackson2.5.0.jar ...

  6. SpringMVC返回JSON数据时日期格式化问题

    https://dannywei.iteye.com/blog/2022929 SpringMVC返回JSON数据时日期格式化问题 博客分类: Spring   在运用SpringMVC框架开发时,可 ...

  7. springmvc 返回json数据给前台jsp页面展示

    spring mvc返回json字符串的方式 方案一:使用@ResponseBody 注解返回响应体 直接将返回值序列化json            优点:不需要自己再处理 步骤一:在spring- ...

  8. spring入门(七)【springMVC返回json串】

    现在多数的应用为了提高交互性多使用异步刷新,即在不刷新整个页面的情况下,只刷新局部,局部刷新用得最多就是ajax,ajax和后台进行交互的数据格式使用的最多的是JSON,这里简单描述,在springm ...

  9. springmvc返回json字符串中文乱码问题

    问题: 后台代码如下: @RequestMapping("menuTreeAjax") @ResponseBody /** * 根据parentMenuId获取菜单的树结构 * @ ...

随机推荐

  1. SNAT和DNAT

    1.SNAT iptables防火墙 Centos6.6 64位 iptables 内网:eth0 172.16.4.1 外网:eth 112.112.112.112/24 当有用户访问公网时,修改用 ...

  2. js 函数作为参数+接受任意数量参数

    javascript中的函数是“复合数据类型”,又成为“引用类型”.引用类型的变量指向存储单元中存放的是它们的实际存放地址.函数名是对函数的一种引用.var a=max_num ;a()就可以调用fu ...

  3. css样式显示省略号

     用css样式显示省略号,记 .xx{ display: block; width:200px;/*对宽度的定义,根据情况修改*/ overflow: hidden; white-space: n ...

  4. 20155207 《网络对抗技术》EXP3 免杀原理与实践

    20155207 <网络对抗技术>EXP3 免杀原理与实践 基础问题回答 杀软是如何检测出恶意代码的? - 根据特征码进行检测(静态) - 启发式(模糊特征点.行为 ) - 根据行为进行检 ...

  5. idea 中全局查找不到文件 (两shift),单页搜索不到关键字的原因

    全局查找不到文件是因为把要找的目录的本级或者上级设置为了额外的,所以自然找不到 而单页搜索不到内容是因为设置了words关键字,这个要全部都输入完才能找到(也就是整个关键字进行匹配,匹配到了整体才会查 ...

  6. maven常用命令集

    maven常用命令 mvn compile  编译主程序源代码,不会编译test目录的源代码.第一次运行时,会下载相关的依赖包,可能会比较费时间. mvn test-compile  编译测试代码,c ...

  7. R语言学习 第一篇:变量和向量

    R是向量化的语言,最突出的特点是对向量的运算不需要显式编写循环语句,它会自动地应用于向量的每一个元素.对象是R中存储数据的数据结构,存储在内存中,通过名称或符号访问.对象的名称由大小写字母.数字0-9 ...

  8. djbc

    jdbc:mysql://localhost:3306:test这句里面分如下解析:jdbc:mysql:// 是指JDBC连接方式:localhost: 是指你的本机地址:3306 SQL数据库的端 ...

  9. 冲刺Two之站立会议3

    今天继续昨天的工作,对主界面进行设计优化,并成功将各个按钮和对应的功能模块连接了起来.并对服务器部分进行了部分改进,包括登录界面的美观性和服务器数据库部分的处理.

  10. 冲刺Two之站立会议1

    今天我们开始了第二个冲刺期的工作,大家重新讨论了下个阶段的工作内容,由于上次演示我们主要只是实现了摄像头开启.通信和语音通话的功能,而且各部分还有待完善.所以我们决定了之后的主要工作的内容:之前服务器 ...