使用SSM搭建Web系统时,在spring-mvc.xml中配置了返回json的格式,使用的是com.alibaba.fastjson的包,具体配置如下
application/json;charset=UTF-8
text/html;charset=UTF-8
application/json;charset=UTF-8
在控制器中测试代码
@RequestMapping(value="/menulist")
@ResponseBody
public Object menulist() {
List adminmenu =adminmenumapper.selectmenulist();
return JSON.toJSONString(adminmenu);
}
虽然这个返回的数据格式为JSON格式,但是总感觉少了点什么,应为之前使用PHP返回的JSON格式是长这样的
然后查看测试返回的JSON数据的头,发现response 的content type是
Content-Type | text/html; charset=utf-8 |
这不是我们期望的,我们期望的response content type
Content-Type | text/html; charset=utf-8 |
通过注解@RequestMapping 中的produces="application/json;charset=UTF-8",动态设置返回数据格式,
使用上述spring-mvc.xml的配置,默认的返回格式是
Content-Type | text/html; charset=utf-8 |
所以在控制器下的@RequestMapping注解中需要动态设置Content-Type返回格式
Content-Type类型主要有:text/html;charset=UTF-8、text/plain;charset=UTF-8、application/json;charset=UTF-8、application/octet-stream
用法如下:
@RequestMapping(value="/menulistjson",produces="application/json;charset=UTF-8")
@ResponseBody
public Object menulistjson() {
List adminmenu =adminmenumapper.selectmenulist();
return JSON.toJSONString(adminmenu);
}
附spring官方文档
spring MVC官方文档:
Producible Media Types
You can narrow the primary mapping by specifying a list of producible media types. The request will be matched only if the Accept request header matches one of these values. Furthermore, use of the produces condition ensures the actual content type used to generate the response respects the media types specified in the producescondition. For example:
@Controller @RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json") @ResponseBody public Pet getPet(@PathVariable String petId, Model model) { // implementation omitted }
Just like with consumes, producible media type expressions can be negated as in !text/plain to match to all requests other than those with an Accept header value oftext/plain.
Tip
The produces condition is supported on the type and on the method level. Unlike most other conditions, when used at the type level, method-level producible types override rather than extend type-level producible types. |