Skip to content

Instantly share code, notes, and snippets.

@abhirockzz
Last active March 27, 2016 09:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abhirockzz/23bc720359ac7cd76d18 to your computer and use it in GitHub Desktop.
Save abhirockzz/23bc720359ac7cd76d18 to your computer and use it in GitHub Desktop.
Improving GET request performance in JAX-RS by using the Last-Modified and If-Modified-Since headers
@Path("books")
@Stateless
public class BooksResource_1{
@PersistenceContext
EntityManager em;
@Context
Request request;
@Path("{id}")
@GET
@Produces("application/json")
public Response getById(@PathParam("id") String id){
Book book = em.find(Book.class, id); //get book info from backend DB
Date lastModified = book.getLastModified(); //get last modified date
ResponseBuilder evaluationResultBuilder = request.evaluatePreconditions(lastModified); //let JAX-RS do the math!
if(evaluationResultBuilder == null){
evaluationResultBuilder = Response.ok(book); //resource was modified, send latest info (and HTTP 200 status)
}else{
System.out.println("Resource not modified - HTTP 304 status");
}
CacheControl caching = ...; //decide caching semantics
evaluationResultBuilder.cacheControl(caching)
.header("Last-Modified",lastModified); //add metadata
return evaluationResultBuilder.build();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment