spring mvc设置应答体的content type

 

 spring MVC中如何设置应答体的content type呢?

spring MVC中如何设置返回类型呢?

我们知道response 的content type主要有:

text/html

text/plain

application/json;charset=UTF-8

application/octet-stream

先举一个例子,spring mvc中可以通过如下方式返回json字符串:

@ResponseBody  
    @RequestMapping(value = "/upload")  
    public String upload(HttpServletRequest request, HttpServletResponse response,String contentType2)  
            throws IOException {  
        String content = null;  
        Map map = new HashMap();  
        ObjectMapper mapper = new ObjectMapper();  
  
        map.put("fileName", "a.txt");  
        try {  
            content = mapper.writeValueAsString(map);  
            System.out.println(content);  
        } catch (JsonGenerationException e) {  
            e.printStackTrace();  
        } catch (JsonMappingException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
          
        return content;  
  
    } 

 

 

虽然访问时返回的确实是json字符串,但是response 的content type是"

text/html

"这不是我们期望的,我们期望的response content type是"application/json"或者"application/json;charset=UTF-8",那么如何实现呢?

通过注解@RequestMapping 中的produces

用法如下:

 

@RequestMapping(value = "/upload",produces="application/json;charset=UTF-8")  

 

 

 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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值