Add an Expires or a Cache-Control header in JSP

大兔子大兔子 提交于 2019-11-26 12:02:31

问题


How do you add an Expires or a Cache-Control header in JSP? I want to add a far-future expiration date in an include page for my static components such as images, CSS and JavaScript files.


回答1:


To disable browser cache for JSP pages, create a Filter which is mapped on an url-pattern of *.jsp and does basically the following in the doFilter() method:

HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1
httpResponse.setHeader("Pragma", "no-cache"); // HTTP 1.0
httpResponse.setDateHeader("Expires", 0); // Proxies.

This way you don't need to copypaste this over all JSP pages and clutter them with scriptlets.

To enable browser cache for static components like CSS and JS, put them all in a common folder like /static or /resources and create a Filter which is mapped on an url-pattern of /static/* or /resources/* and does basically the following in the doFilter() method:

httpResponse.setDateHeader("Expires", System.currentTimeMillis() + 604800000L); // 1 week in future.

See also:

  • Making sure a web page is not cached, across all browsers.
  • Webapplication performance tips and tricks.



回答2:


<%
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);
%>



回答3:


<%
    response.setHeader("Cache-Control", "no-cache"); //HTTP 1.1
    response.setHeader("Pragma", "no-cache"); //HTTP 1.0
    response.setDateHeader("Expires", 0); //prevents caching at the proxy server
%>



回答4:


Servlet containers like Tomcat come with a set of predefined filters. See for example Expires Filter. It may be easier to use existing one than to create your own similar filter.



来源:https://stackoverflow.com/questions/3055268/add-an-expires-or-a-cache-control-header-in-jsp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!