Xml代码 
<bean class ="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" >  
    <property name="messageConverters">  
  <list>  
   <ref bean="mappingJacksonHttpMessageConverter" /><!-- json转换器 -->  
  </list>  
</property>  
</bean>      
<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />

<bean class ="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" > 
    <property name="messageConverters"> 
  <list> 
   <ref bean="mappingJacksonHttpMessageConverter" /><!-- json转换器 --> 
  </list> 
</property> 
</bean>   
<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />

需要以下两个jar包:

Xml代码 
<dependency org="org.codehaus.jackson" name="jackson-core-asl" rev="1.5.5" conf="runtime->default" />  
<dependency org="org.codehaus.jackson" name="jackson-mapper-asl" rev="1.5.5" conf="runtime->default" />

<dependency org="org.codehaus.jackson" name="jackson-core-asl" rev="1.5.5" conf="runtime->default" /> 
<dependency org="org.codehaus.jackson" name="jackson-mapper-asl" rev="1.5.5" conf="runtime->default" />

Java代码 
@RequestMapping(value="/nogood", method=RequestMethod.GET)   
public @ResponseBody CmUser execute(String userid) {   
  CmUser u = new CmUser();   
  u.setAge(16);   
  u.setName("测试用户");   
  return u;   
}

通过上面的代码可以实现java对象直接可以转json对象,下面是项目中的配置

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="webBindingInitializer">
            <bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
                <property name="conversionService" ref="conversionService"/>
            </bean>
        </property>
        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
                <bean class="org.springframework.http.converter.StringHttpMessageConverter" >
                    <property name = "supportedMediaTypes">
                           <list>
                                   <value>text/plain;charset=UTF-8</value>
                          </list>
                     </property> 
                </bean>
                <bean class="org.springframework.http.converter.ResourceHttpMessageConverter" />
                <!-- 注:开启此类需相关jar包持:javax.xml.bind.JAXBException
                <bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter" />
                <bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter" />
                <bean class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter" />
                 -->
                <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
            </list>
        </property>
    </bean>

下面分析@ResponseBody 注解

在SpringMVC中可以在Controller的某个方法上加@ResponseBody注解,表示该方法的返回结果直接写入HTTP response body中。

但是实际使用中发现最后生成的response中"Content-Type"的值不正确。

Spring使用AnnotationMethodHandlerAdapter来处理@ResponseBody,该类再使用一些HttpMessageConverter来具体处理信息。

AnnotationMethodHandlerAdapter使用request header中"Accept"的值和messageConverter支持的MediaType进行匹配,然后会用"Accept"的第一个值写入 response的"Content-Type"。

一般的请求都是通过浏览器进行的,request header中"Accept"的值由浏览器生成。

Chrome生成的值为application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5

IE8生成的值为application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*

所以最后写入response中"Content-Type"的值为"application/xml"或"application/x-ms-application"。

但我们一般会在标注@ResponseBody的方法上返回String或byte[]类型的结果,期望的"Content-Type"的值应为"text/plain"或"application/octet-stream"。

这样导致了浏览器不能正确处理返回的内容。

实际上Spring在用HttpMessageConverter处理的过程中首先会判断response header中有没有写入"Content-Type",如果没有写入的话才会使用request header中"Accept"的第一个值。

但是由于Spring对HttpServletResponse进行了封装,实际上使用的是ServletServerHttpResponse,这个类有一个对真正的HttpServletResponse的引用。

判断response header的过程中使用的是ServletServerHttpResponse的getHeaders()方法,但该方法并没有返回真正的HttpServletResponse中的header。(这应该有问题吧?)

所以我们虽然可以在Controller的方法中加入对HttpServletResponse的引用,然后设置"Content-Type"的值,但是并不会起作用。

通过上面的分析,@ResponseBody看来是无法使用了。

还可以参考下面文章:http://www.iteye.com/topic/1124054
http://www.360doc.com/content/12/0809/11/9600761_229177035.shtml

 
0

spring mvc Response header content type的更多相关文章

  1. ASP.NET MVCでResponse Headerのサーバーバージョンをどうやって隠しますか?

    本来是发布在客户的Wiki上的,所以用日语写. ---------------------------------------------------------------------------- ...

  2. 从content-type设置看Spring MVC处理header的一个坑

    我们经常需要在HttpResponse中设置一些headers,我们使用Spring MVC框架的时候我们如何给Response设置Header呢? Sooooooooooooo easy, 看下面的 ...

  3. spring mvc获取header

    两种方法: 1.在方法参数中加入@RequestHeader 2.在类级别注入HttpServletRequest 建议使用第二种方法,这样可避免每个方法都加入HttpHeaders参数 @Contr ...

  4. spring MVC之返回JSON数据(Spring3.0 MVC)

    方式一:使用ModelAndView的contentType是"application/json" 方式二:返回String的            contentType是&qu ...

  5. 零基础搭建 spring mvc 4 项目(本文基于 Servlet 3.0)

    作者各必备工具的版本如下: Tomcat:apache-tomcat-7.0.63 (下载链接) Java EE - Eclipse:Luna Service Release 1 v4.4.1 (下载 ...

  6. ajax使用向Spring MVC发送JSON数据出现 org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported错误

    ajax使用向Spring MVC发送JSON数据时,后端Controller在接受JSON数据时报org.springframework.web.HttpMediaTypeNotSupportedE ...

  7. Spring MVC Content Negotiation 转载

    Spring MVC Content Negotiation 2017年11月15日 00:21:21 carl-zhao 阅读数:2983   Spring MVC有两种方式生成output的方法: ...

  8. Content Negotiation using Spring MVC

    There are two ways to generate output using Spring MVC: You can use the RESTful @ResponseBody approa ...

  9. springboot Serving Web Content with Spring MVC

    Serving Web Content with Spring MVC This guide walks you through the process of creating a "hel ...

随机推荐

  1. 压力测试-jmeter

    1. 场景描述 新申请的服务器,要压测下python算法程序最多能执行多少条数据,有几年没用压力测试工具-jmeter了,重新下载了最新版本,记录下,也希望能帮到准备使用jmeter做压测的朋友. 2 ...

  2. Yii CGridView 之 SQL 语句

    在CGridView里,有时候需要用到复杂的查询时,可用 CSqlDataProvider替换CActiveDataProvider, CSqlDataProvider 可用复杂的查询语句,例子如下: ...

  3. Django Mysql数据库-基于双下划线的跨表查询

    一.基于双下划线的跨表查询 Django 还提供了一种直观而高效的方式在查询(lookups)中表示关联关系,它能自动确认 SQL JOIN 联系.要做跨关系查询,就使用两个下划线来链接模型(mode ...

  4. 《深入理解Java虚拟机》- JVM是如何实现反射的

    Java反射学问很深,这里就浅谈吧.如果涉及到方法内联,逃逸分析的话,我们就说说是什么就好了.有兴趣的可以去另外看看,我后面可能也会写一下.(因为我也不会呀~) 一.Java反射是什么? 反射的核心是 ...

  5. C++函数中,两个自动释放内存的动态内存申请类

    最近做一个事情,实现一个流程交互,其中主交互流程函数中,涉及较多的内存申请, 而健康的函数,都是在函数退出前将手动申请不再需要的内存释放掉, 使用很多方法,都避免不了较多的出错分支时,一堆的if fr ...

  6. RabbitMQ的各个参数

    简介 原文:https://blog.csdn.net/vbirdbest/article/details/78670550 本节主要讨论队列声明的各个参数 queueDeclare(String q ...

  7. python 13 内置函数2

    目录 内置函数(二) 匿名函数 内置函数(三) 闭包 内置函数(二) abs() #返回绝对值--返回的是正数 enumerate("可迭代对象","序号起始值" ...

  8. 剖析nsq消息队列(一) 简介及去中心化实现原理

    分布式消息队列nsq,简单易用,去中心化的设计使nsq更健壮,nsq充分利用了go语言的goroutine和channel来实现的消息处理,代码量也不大,读不了多久就没了.后期的文章我会把nsq的源码 ...

  9. 在SpringMVC中,jsp和后台互相传值

    如题,这个是以前做的笔记,现在搬到博客上...... package com.ruide.action; ​ import java.util.HashMap; import java.util.Ma ...

  10. 各IDE代码自用开头模板

    Pycharm #!/usr/bin/env python # -*- coding: utf-8 -*- # @version : 1.0 # @Time : ${DATE} ${TIME} # @ ...