Page caching problem
I use JSP (Spring MVC) for showing information to remote user. I have some problems with caching of page. It looks like this:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>My Title</title>
</head>
<body>
<jsp:include page="menu.jsp" flush="true" />
<form method="post">
Write here
<input type="text" name="inputTxt" value="${txt}" />
<input type="submit" value="OK" />
</form>
<table border="1">
...
</table>
</body>
</html>
Page should show a table of items. When user press OK button, server add information to the database and add a row to the table. All wo开发者_运维技巧rks fine. But tables shows an information depends on the logged user. So, when I login for the first time, my app works great (shows me the data, corresponding to the current user). But when I logout from current user and login from new, this page still show data for firs user. If I press F5, table update it's data and shows correct information, which corresponds to the current user. I think problems with caching. How to avoid this problem? Any ideas?
The page is indeed likely cached by the browser. You can verify this in Firefox with Firebug. Generally, you would like to disable client side caching of dynamic content. You can achieve this by creating a Filter
which is mapped on an url-pattern
of *.jsp
and does basically the following job 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.
chain.doFilter(request, response);
Those response headers will instruct the client (webbrowser) to not cache the response. Don't forget to clean the browser cache before testing.
In Spring MVC, you can create an interceptor like so:
public class DisableBrowserCachingInterceptor extends HandlerInterceptorAdapter {
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1
response.setHeader("Pragma", "no-cache"); // HTTP 1.0
response.setDateHeader("Expires", 0); // Proxies
}
}
精彩评论