场景:方便使用spring mvc生成json,并且兼容ie,chrome....

设计:手工指定RequestMappingHandlerMapping和RequestMappingHandlerAdapter,并给RequestMappingHandlerAdapter的messageConverters的注入属性值.不使用驱动注解(<mvc:annotation-driven />)自动配置的原因是:自动配置我没找到方法来修改response的Content-Type, 而自动配置默认的content-type是application/json;charset=UTF-8.这个contentType在谷歌浏览器很正常解析,而到了IE解析为弹出下载了,IE10,IE11一样不给面子!!!如果将contentType改为:text/html;charset=UTF-8.那IE和google浏览器都能正常解析了.


不用再去写<mvc:annotation-driven />,至于<mvc:annotation-driven />在背后做了什么,可看参考手册.注意spring版本哦,这两类从3.1才开始有的.


基于xml配置:

	<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />
	<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
		<property name="messageConverters">
			<list>
				<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
					<property name="supportedMediaTypes">
						<list>
							<value>text/html;charset=UTF-8</value>
							<value>application/json;charset=UTF-8</value>
						</list>
					</property>
				</bean>
			</list>
		</property>
	</bean>

基于Java-config方式会更加简单一点,先让你的mvc配置继承WebMvcConfigurerAdapter,再重写configureMessageConverters方法,加入jackson包,在controller使用@ResponseBody注解,OK!

如果要全局支持jsonp(支持jsonp的做法:可以在controller的方法返回String类型,接收一下callback,然后callback调用一下json结果就可以),可以再加一个StringHttpMessageConverter,不仅能解决中文乱码,还能把json里面的换行\r\n去掉.

    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                    <property name="supportedMediaTypes">
                        <list>
                            <value>text/html; charset=UTF-8</value>
                            <value>application/json;charset=UTF-8</value>
                        </list>
                    </property>
                </bean>
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                    <property name="supportedMediaTypes">
                        <list>
                            <value>text/html; charset=UTF-8</value>
                            <value>application/json;charset=UTF-8</value>
                        </list>
                    </property>
                </bean>
            </list>
        </property>
    </bean>


GitHub 加速计划 / js / json
41.72 K
6.61 K
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:8 天前 )
960b763e 2 个月前
8c391e04 5 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐