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. Oracle 解决【ORA-01704:字符串文字太长】

    错误提示:oracle在toad中执行一段sql语句时,出现错误‘ORA-01704:字符串文字太长’.如下图: 原因:一般为包含有对CLOB字段的数据操作.如果CLOB字段的内容非常大的时候,会导致 ...

  2. 汇编 inc 和 dec 指令

    知识点: inc 加1指令 dec 减1指令 一.加一指令inc inc a 相当于 add a, //i++ 优点 速度比sub指令快,占用空间小 这条指令执行结果影响AF.OF.PF.SF.Z ...

  3. 汇编 sub减法指令 比较指令CMP JZ条件跳转指令

    二.SUB指令 减法指令SUB (SUBtract) 格式: SUB A,B //A=A-B; 功能: 两个操作数的相减,即从A中减去B,其结果放在A中. 二.CMP 和JZ 指令 比较指令CMP 格 ...

  4. 带阴影的圆形 QLabel

    带阴影的圆形 Label 来自: 公孙二狗

  5. 洛咕 P3706 [SDOI2017]硬币游戏

    假设f[i]是第i个同学胜利的概率,也就是随机序列第一个匹配到s[i]的概率 假设前面有一个字符串\(S\),(假设无限长但没有匹配),现在往后面要加上第i个串\(s[i]\),这个的概率设为\(P_ ...

  6. 新员工入门 - for测试

    23456人员介绍 XXX 测试工作 [软件] Chrome 浏览器.jsonviewer.Firefox.FireBug HTTP协议与抓包 - fildder.wireshirk等 DB查询工具 ...

  7. laraver框架学习------工厂模型填充测试数据

    在laravel中填充数据有几种方式.一种是Seeder,另一种是工厂模式进行的填充. 工厂模式可以实现大批量的填充数据,数据的量可以自定义.这也为后续的软件测试提供方便. 在laravel框架有da ...

  8. 解决SSH登录用户执行的命令部分环境变量参数不生效的问题

    问题概况 linux机器在/etc/profile配置完成环境变量后,SSH到目标机器执行命令,但是获取不到已配置的环境变量值. 例如场景: 在/etc/profile配置了http代理 export ...

  9. python3 subprocess模块

    当我们在执行python程序的时候想要执行系统shell可以使用subprocess,这时可以新起一个进程来执行系统的shell命令,python3常用的有subprocess.run()和subpr ...

  10. tornado学习笔记

    一.UIMOTHODS: 1.在项目目录创建uimothods.py文件(名称可以任意)内容: def test2(self): return ('hello uimothods') 2.tornad ...