springmvc controller动态设置content-type

  springmvc  RequestMappingHandlerAdapter#invokeHandlerMethod 通过ServletInvocableHandlerMethod#invokeAndHandle调用目标方法,并处理返回值。

  

  如果return value != null,则通过returnvalueHandlers处理,内部会调用MessageConverter转换成相应的报文格式。

  

  HttpOutputMessage outputMessage 对应的实例 是 org.springframework.http.server.ServletServerHttpResponse。
  在写入数据的同时,会设置response的header,包括content-type(根据RequestMapping 的 produces 属性 计算出来)。
  所以,在带有返回值的情况下,在controller中设置content-type是无效的,会被消息转换器覆盖掉。
  
@RequestMapping(value = "xxx", method = {RequestMethod.POST, RequestMethod.GET})
@ResponseBody
public String handleKafkaSpecialMessage(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType("application/json");
    return "xxx";
}

  改一下返回值就好了

@RequestMapping(value = "xxx", method = {RequestMethod.POST, RequestMethod.GET})
@ResponseBody
public void handleKafkaSpecialMessage(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType("application/json");
    try(OutputStream ros = response.getOutputStream()) {
        IOUtils.write("xxx", ros);
        ros.flush();
    } catch (IOException e) {
    }
}

 

posted @ 2018-08-02 09:24  hjzqyx  阅读(11583)  评论(1编辑  收藏  举报