Using the Expires header to control the validity of the HTTP cache

You can use the Expires HTTP header field to let all entities involved in the request-response chain know when a resource has expired. The Expires HTTP header was defined as part of the HTTP/1.0 specification. You can specify the date and time in the Expires header, after which the resource fetched from the server is considered stale.

The following code snippet shows how you can add the Expires HTTP header to the resource returned by the method:

@GET 
@Path("departments/{id}/holidays") 
@Produces(MediaType.APPLICATION_JSON) 
public Response getHolidayListForCurrentYear(@PathParam("id") 
Short deptId) { //Reads the list of holidays List<Date> holidayList = getHolidayListForDepartment(deptId); //Build response Response.ResponseBuilder response = Response.ok(holidayList). type(MediaType.APPLICATION_JSON); //Set the expiry for response resource //This example sets validity as //Dec 31 of the current year int currentYear = getCurrentYear(); Calendar expirationDate = new GregorianCalendar (currentYear,12, 31); response.expires(expirationDate.getTime()); return response.build(); }

Here is the sample response header generated by the preceding method for the GET departments/10/holidays HTTP/1.1 request:

Server: GlassFish Server Open Source Edition 4.1  
Expires: Sat, 31 Dec 2015 00:00:00 GMT  
Content-Type: application/json  
Date: Mon, 02 Mar 2015 05:24:58 GMT  
Content-Length: 20  

Expires headers are good for the following uses:

  • Making static resources returned by the server, such as images, cacheable.
  • Controlling the caching of a resource returned by servers that changes only at specific intervals. For instance, a list of public holidays for an organization for a specific year, which does not usually change within a year.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.36.194