Add expires headers to the component to maximize browser caching

Source: Internet
Author: User
Tags log log website performance

Once the Web project is deployed, the pictures, CSS, and JS in the project are rarely changed, so if the components are cached in the browser client instead of being fetched from the server, the site's visitors will be heavily relieved of the server's request after the first visit to the site. This move, which brings performance improvements, can be called perfect! So how do you do it? That is to add the expires (term) header to the component!

First, understand expires head

At first, when reading the "High Performance Web Site Guide" Chapter III "Add Expires Head", feel very stressed, because do not understand what expires head is to do, so there is no mind to practice the practice, on the shelf for a period of time. However, today is a good mood, resistant to looking for a series of resources on the Internet, and reread this article, practice repeatedly, finally fix, hereby share, hope more friends can see, practice into your project, thereby improving website performance.

I offer a few articles for everyone to read:

    1. TOMCAT7 The official doc in the Expires_filter, can be combined with the source code for analysis.
    2. Browser Cache Detailed parsing
    3. HTTP1.1 protocol
    4. Website Performance optimization: Cache-control Setup

With these articles as a cushion, I think you can basically understand expires head.

Second, the effect

For a added expires header of the CSS, its request for information, more max-age, and expires, the relationship between the two I will not repeat, the previous article described more clearly.

Third, the realization method ①, new Cachecontrolfilter.java
 PackageCom.honzh.common.filter;ImportJava.io.IOException;ImportJava.util.Calendar;ImportJava.util.Date;ImportJava.util.Enumeration;ImportJavax.servlet.Filter;ImportJavax.servlet.FilterChain;ImportJavax.servlet.FilterConfig;ImportJavax.servlet.ServletException;ImportJavax.servlet.ServletRequest;ImportJavax.servlet.ServletResponse;ImportJavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportOrg.apache.commons.logging.Log;ImportOrg.apache.commons.logging.LogFactory; Public  class cachecontrolfilter implements Filter {    PrivateFilterconfig config =NULL;Private Static FinalString Cache_control_by_type ="Cache-control";Private Static FinalString header_expires ="Expires";Private Static FinalLog log = Logfactory.getlog (Cachecontrolfilter.class); Public void DoFilter(ServletRequest request, servletresponse response, Filterchain chain)throwsIOException, Servletexception {if(RequestinstanceofHttpServletRequest && ResponseinstanceofHttpServletResponse) {HttpServletResponse HttpResponse = (httpservletresponse) response; HttpServletRequest HttpRequest = (httpservletrequest) request;BooleanCachecontrolset =false; for(enumeration<string> names = Config.getinitparameternames (); names.hasmoreelements ();)                {String headername = (string) names.nextelement (); Log.debug ("parameter name:"+ headername);                String value = Config.getinitparameter (headername); Log.debug ("parameter value:"+ value);//Description contains the type, at which point you want to filter the type that meets the criteriaString type = headername.substring (Cache_control_by_type.length ()). Trim (); Log.debug ("The type specified by the parameter:"+ type); String ContentType = Httprequest.getheader ("Accept"); Log.debug ("Request Content Type is:"+ ContentType);if(Contains (ContentType,";")) {//Lookup Content-type without charset match (e.g.                    //"text/html")String Contenttypewithoutcharset = Substringbefore (ContentType,";"). Trim ();if(Contenttypewithoutcharset.indexof (type)! =-1) {//Type match, then see if value is Max-age, if yes, set Max-age to current time + 1 monthsCalendar calendar = Calendar.getinstance (); Calendar.settime (NewDate ()); Calendar.add (Calendar.month,1);                        Date expirationdate = Calendar.gettime ();                        Httpresponse.setdateheader (Header_expires, Expirationdate.gettime ()); String maxagedirective ="Max-age="+ ((Expirationdate.gettime ()-System.currenttimemillis ())/ +); Setcontrolheader (HttpResponse,"Private,"+ maxagedirective); Cachecontrolset =true; }                }            }if(!cachecontrolset) {Setcontrolheader (HttpResponse,"Private"); }} chain.dofilter (request, response);//Resp.setheader ("Expires", "Tue, Jul 2001 06:00:00 GMT");        //Resp.setdateheader ("Last-modified", New Date (). GetTime ());        //Resp.setheader ("Cache-control",        //"No-store, No-cache, Must-revalidate, max-age=0, post-check=0, pre-check=0");        //Resp.setheader ("Cache-control", "private");        //Resp.setheader ("Pragma", "No-cache");}Private void Setcontrolheader(HttpServletResponse HttpResponse, String Cache_control)        {String Cachecontrolheader = Httpresponse.getheader (Cache_control_by_type); String Newcachecontrolheader = (Cachecontrolheader = =NULL) ? Cache_control:cachecontrolheader +", "+ Cache_control;    Httpresponse.setheader (Cache_control_by_type, Newcachecontrolheader); }@Override     Public void Destroy() {    }@Override     Public void Init(filterconfig config)throwsservletexception { This. config = config; }protected Static Boolean contains(String str, string searchstr) {if(str = =NULL|| Searchstr = =NULL) {return false; }returnStr.indexof (SEARCHSTR) >=0; }protected StaticStringSubstringbefore(String str, string separator) {if(str = =NULL|| Str.isempty () | | Separator = =NULL) {return NULL; }if(Separator.isempty ()) {return ""; }intSeparatorindex = Str.indexof (separator);if(Separatorindex = =-1) {returnStr }returnStr.substring (0, Separatorindex); }}
    1. In Web. XML, we set three types for expires, with detailed parameters for image, CSS, and Js,②, so that in filter we will add expires, Max-age for these three types.
    2. As for the private that is mentioned in the class, you can focus on my other article gzip compressed Tomcat server response package, which greatly improves Web performance.
    3. Other aspects, the code is not complex, the main thing is the practice, I will practice to provide to everyone.
②, Web. xml
<filter>        <filter-name>Cachecontrolfilter</filter-name>        <filter-class>Com.honzh.common.filter.CacheControlFilter</filter-class>        <init-param>            <param-name>Cache-control image</param-name>            <param-value>Max-age</param-value>        </init-param>        <init-param>            <param-name>Cache-control Text/css</param-name>            <param-value>Max-age</param-value>        </init-param>        <init-param>            <param-name>Cache-control Application/javascript</param-name>            <param-value>Max-age</param-value>        </init-param>    </filter>    <filter-mapping>        <filter-name>Cachecontrolfilter</filter-name>        <url-pattern>/*</url-pattern>    </filter-mapping>

Above, two steps (add Expires header for component) after completion, your project will have a further improvement in performance, how does it feel?

Add expires headers to the component to maximize browser caching

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.