springmvc controller动态设置content-type

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

  springmvc controller动态设置content-type

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

  springmvc controller动态设置content-type

  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) {
}
}
上一篇:linux centos ubentu安装IPython四种方法


下一篇:Solving the Top ERP and CRM Metadata Challenges with erwin & Silwood