Conditional request processing with the Last-Modified HTTP response header

The Last-Modified header field value in HTTP is often used for validating the cached response contents. The Last-Modified entity-header field indicates the date and time at which the entity present in the response body was last modified. A client can use the Last-Modified header field value in combination with the If-Modified-Since or If-Unmodified-Since request headers to perform conditional requests.

The following example illustrates the use of the Last-Modified HTTP header field in the JAX-RS application. The Last-Modified field contains the date when the resource was last changed. When a client requests the same resource next time, it sends the If-Modified-Since header field, with the value set to the date and time at which the resource was last updated on the server. On the server, you can call javax.ws.rs.core.Request::evaluatePreconditions() to check whether the resource has been modified in between the requests. This method evaluates request preconditions on the basis of the passed-in value. If this method returns null, the resource is out of date and needs to be sent back in the response. Otherwise, this method returns the 304 Not Modified HTTP status code to the client. Here is the code snippet for this example:

//Other imports are removed for brevity 
import javax.ws.rs.core.Request;  
import javax.ws.rs.core.Context; 
import javax.ws.rs.core.Response.ResponseBuilder; 
 
@GET 
@Path("departments/{id}") 
@Produces(MediaType.APPLICATION_JSON) 
public Response 
findDepartmentWithCacheValidationWithLastModifiedDate( @PathParam("id") Short id, @Context Request request) { //Reads the latest Department object from DB Department department = entityManager.find(Department.class, id); //Gets the last modified date Date latModifiedDate = department.getModifiedDate(); //Evaluates request preconditions on the basis //of the passed-in value. //evaluatePreconditions() return null If-Modified-Since //check succeeds. This implies that resource is modified ResponseBuilder builder = request.evaluatePreconditions(latModifiedDate); //cached resource did change; send new one if (builder == null) { builder = Response.ok(department); builder.lastModified(latModifiedDate); } return builder.build(); }
To learn more about the javax.ws.rs.core.Request::evaluatePreconditions() method, read the API documentation available at https://jax-rs-spec.java.net/nonav/2.0/apidocs/javax/ws/rs/core/Request.html.
..................Content has been hidden....................

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