Wednesday, May 07, 2008

Images cache

One useful trick with Expires filter. This filter lets you set Expires and Cache-Control headers for the serviced responses. By this way your web application may deploy client-side cache for the requested resources. For example, you may decide cache all the requested images on the client's box. So for the sub sequential requests images will be served from right the local computer, and your own server will be free from this task. This simple idea lets actually save a lot of server's resources. How does it work:

1. Describe Expires filter in your web.xml file. An initial parameter expires sets here ttl for cache in seconds (24 hours in this example):

<filter>
<filter-name>ExpiresFilter</filter-name>
<filter-class>com.cj.expire.ExpiresFilter</filter-class>
<init-param>
 <param-name>expires</param-name>
 <param-value>86400</param-value>
</init-param>
</filter>

2. Set a mapping.

<filter-mapping>
 <filter-name>ExpiresFilter</filter-name>
 <url-pattern>*.gif</url-pattern>
</filter-mapping>

<filter-mapping>
 <filter-name>ExpiresFilter</filter-name>
 <url-pattern>*.jpg</url-pattern>
</filter-mapping>

...

Now the mapped files (gif, png etc.) will be cached on the client side

No comments: