首先说一下,静态资源的缓存没有问题,该问题是关于动态内容的缓存,需求是获取各国家列表,因为国家列表内容相对稳定些,所以想利用缓存节省不必要的开销。
代码如下:
-
用于获取各国家列表的 Controller:
@Controller @RequestMapping("/country") public class CountryController{ @Autowired private CountryService countryService; @RequestMapping(method=RequestMethod.GET) public ModelAndView show(){ ModelAndView mav = new ModelAndView(); mav.addObject("countryMap", countryService.getCountries()); mav.setViewName("test"); return mav; } }
-
缓存拦截器配置
<mvc:interceptor> <mvc:mapping path="/country*" /> <bean class="org.springframework.web.servlet.mvc.WebContentInterceptor" > <property name="cacheMappings"> <map> <entry key="/country.json" value="31536000"></entry> <entry key="/country" value="31536000"></entry> </map> </property> </bean> </mvc:interceptor>
当请求 http://host:port/app/country 时,请求头信息和响应头信息如下:
Request Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Accept-Encoding:gzip,deflate,sdch Accept-Language:zh-CN,zh;q=0.8 Cache-Control:max-age=0 Connection:keep-alive Cookie:JSESSIONID=FE1D5C67B795BEBB40C2A72367170A52 Host:localhost:8080 User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36
Response Cache-Control:max-age=31536000 Content-Language:zh-CN Content-Length:4033 Content-Type:text/html;charset=UTF-8 Date:Sun, 23 Mar 2014 11:25:19 GMT Expires:Mon, 23 Mar 2015 11:25:19 GMT Server:Apache-Coyote/1.1
响应头信息中的 Cache-Control 和 Expires 都正确,多次刷新页面,通过浏览器调试工具查看,并没有从缓存中获取内容,希望懂的朋友帮忙找找原因。