spring mvc 3.0 json 操作中定制 http header.

大家都知道springmvc3.0中的JSON响应用起来很方便的,用@ResponseBody标记,然后handler的方法的返回值设为Object.但是现在的问题是这样不能够定制Httpheader.

之前有网友称使用HttpEntity.具体怎么用我也不清楚,只是个人感觉用起来不够优雅.所以就有了这个文章,经过一翻尝试.笔者实现了定制Http响应头中的缓存信息,不设这个的话傻傻的IE7会把AJAX请求作缓存.非常讨厌.

具体实现方法是继承org.springframework.http.converter.json.MappingJacksonHttpMessageConverter,如下是我的代码

import java.io.IOException;

import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;

public class NoCacheMappingJacksonHttpMessageConverter extends
		MappingJacksonHttpMessageConverter {

	@Override
	protected void writeInternal(Object o, HttpOutputMessage outputMessage)
			throws IOException, HttpMessageNotWritableException {
		outputMessage.getHeaders().set("Cache-Control", "no-cache");
		super.writeInternal(o, outputMessage);
	}
}

当然也少不了dispatcher-servlet.xml中的配置:

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                    <property name="supportedMediaTypes">
                        <list>
                            <bean class="org.springframework.http.MediaType">
                                <constructor-arg value="text"/>
                                <constructor-arg value="plain"/>
                                <constructor-arg value="utf8"/>
                            </bean>
                        </list>
                    </property>
                </bean>
                <!-- 
                <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
                 -->
                <bean class="com.fpi.mespvc.web.util.NoCacheMappingJacksonHttpMessageConverter"/>
            </list>
        </property>
    </bean>

笔者亲测.完全好用.

相关推荐