SpringMVC 4.3.* 关于ResponseBody的contentType

来源:互联网 发布:l型的橱柜的算法 编辑:程序博客网 时间:2024/06/03 05:26

        我想将@ResponseBody返回的对象以json格式打印在网页里,但是总是提示我下载。这个应该设置ContentType就ok了,我现在使用的4.3.* 的SpringMVC已经实现XML零配置了,但是在找寻关于“如何设置响应报文的ContentType”时,发现还都是xml的配置方式:如下

   <property name="messageConverters">            <list>                <bean class = "org.springframework.http.converter.StringHttpMessageConverter">                   <property name = "supportedMediaTypes">                      <list>                          <value>text/plain;charset=UTF-8</value>                        </list>                   </property>                </bean>            </list>      </property>  


还有人在网上发帖说是通过注解@RequestMapping 中的produces解决,代码如下

@RequestMapping(value = "/upload",produces="text/plain;charset=UTF-8")  
然并卵,估计发贴人自己都没试过,我亲测是没用的,估计这个是设置请求过来的消息头,而非是响应的头吧。


找了老半天还是没有找到如何用注解解决。不知道是SpringMVC没有还是我没找到,如果有大神知道,还请大神留言一下。


最后只找到了一个很尴尬的解决方案,使用ResponseEntity,需要写代码大哭,有点不爽!代码如下:

@RequestMapping("/userlist")@ResponseBodyResponseEntity<List<User>> userList(){logger.info("进入Controller,查询用户list");HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.TEXT_PLAIN);List<User> list = userService.getUserList();return new ResponseEntity<List<User>>(list, headers, HttpStatus.OK);}



我想要的是一句简单的注解能解决呀!!!



0 0
原创粉丝点击