When accessing a web site, the browser needs to load all the files during the first visit. This mainly depends on the server performance, bandwidth, and server cache settings, during the second visit, we can use the client browser cache to store unchanged CSS, JS, IMAGE, and other elements locally without sending requests to the server each time.
We need to distinguish the three HTTP request headers Last-modified \ Cache-Control \ Expires,
Here, the main difference is that Last-modified needs to negotiate with the server each time whether the cache expires. It is mainly used for processing dynamic content cache.
Cache-Control and Expires are requests for the first time, and then the local database determines whether the request has expired. The difference is that Cache-Control is the relative time returned. For example, one hour after the current time Expires, and Expires is the absolute GMT time. For example, it Expires on January 1, 20.14.
(Note that the difference between the time used in win and the GMT time is 8 hours)
For static files such as CSS, JS, and IMAGE files, add a Filter and add the corresponding expiration time to the Response Headers of these files,
The relative expiration time is used here.
Public class ResponseHeaderFilter implements Filter {FilterConfig fc; public void doFilter (ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {String uri = request. getRequestURI (); HttpServletResponse response = (HttpServletResponse) res; if (uri. indexOf ("/css /")! =-1 | uri. indexOf ("/js /")! =-1 | uri. indexOf ("/images ")! =-1) {response. setHeader ("Cache-Control", "public"); // HTTP/1.1 enable Cache response. setHeader ("Pragma", "Pragma"); // HTTP/1.0 enable cache response. setHeader ("Cache-Control", "max-age = 604800, public"); super. doFilter (req, res, chain);} // pass the request/response on chain. doFilter (req, response);} public void init (FilterConfig filterConfig) {this. fc = filterConfig;} public void destroy () {this. fc = null ;}}
In this way, when accessing the files under these URLs for the second time, we will not send requests to the server, but adopt local cache. After using this optimization method, it will take about 3 s to load the system homepage for the first time, the second loading only takes 0.3 S.