gradle配置:
compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.8.7'
SpringMVC配置文件中需要添加如下配置:
<mvc:annotation-driven/>
<mvc:annotation-driven /> 是一种简写形式,完全可以手动配置替代这种简写形式,简写形式可以让初学者快速应用默认配置方案。<mvc:annotation-driven /> 会自动注册RequestMappingHandlerMapping 以及 RequestMappingHandlerAdapter 两个bean,是spring MVC为@Controllers分发请求所必须的。
并提供了:数据绑定支持,@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持,读写XML的支持(JAXB),读写JSON的支持(Jackson)。
后面,我们处理响应ajax请求时,就使用到了对json的支持。
<context:annotation-config>
declares support for general annotations such as @Required, @Autowired, @PostConstruct, and so on.
<mvc:annotation-driven />
is actually rather pointless. It declares explicit support for annotation-driven MVC controllers (i.e.@RequestMapping, @Controller, etc), even though support for those is the default behaviour.
My advice is to always declare <context:annotation-config>, but don't bother with <mvc:annotation-driven /> unless you want JSON support via Jackson.
测试:
package com.xiya.springmvc.handlers; import com.xiya.springmvc.entities.Address; import com.xiya.springmvc.entities.User; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.ArrayList; import java.util.List; /** * Created by N3verL4nd on 2017/4/1. */ @Controller public class JsonTest { @RequestMapping("/ajax2") @ResponseBody public List<User> ajax2() { List<User> list = new ArrayList<>(); Address address = new Address("shandong", "liaocheng"); User user = new User("熙雅", "*****", "*****@qq.com", 24, address); list.add(user); return list; } }
<mvc:annotation-driven/>单独如上设置,在IE浏览器访问,会弹出来下载链接。可以如下设置:
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
这里需要强调一下,JSON默认的MIME类型为application/json,
<value>text/html;charset=UTF-8</value>如果这样设置,你获得到的是JSON字符串,需要使用JSON.parse()或者eval()函数转化为JSON对象。
综上,使用SpringMVC返回json步骤:
1、加入jackson的jar包。
2、编写controller方法,使其返回JSON对应的对象或者集合。
3、在方法上添加@ResponseBody注解。