Last active
March 27, 2016 09:56
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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