Is it possible to set ETags using JAX-RS without resorting to Response objects?

前端 未结 3 479
心在旅途
心在旅途 2021-02-04 10:21

In one of the few questions (with answers) I have found on SO regarding JAX-RS and caching, the answer to generating ETags (for caching) is by setting some values on the Respons

3条回答
  •  悲&欢浪女
    2021-02-04 10:48

    or it can be as simple as sending back an "error" code... depending on what you want to do.

    @Path("/{id}")
    @GET
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    public ProductSearchResultBean getProductById(@PathParam("id") Integer productId, @QueryParam("expand") List expand, @Context HttpServletRequest request, @Context HttpServletResponse response) throws IOException {
    
        ProductSearchResultBean productDetail = loadProductDetail(productId, expand);
    
        EntityTag etag = new EntityTag(((Integer)(productDetail.toString().hashCode())).toString());
        String otherEtag = request.getHeader("ETag");
        if(etag.getValue().equals(otherEtag)){
            response.sendError(304, "not Modified");
        }
    
        response.addHeader("ETag", etag.getValue());
    
        return productDetail;
    }
    

    That's how I tackled the issure anyway. Good luck! (Use Spring MVC instead.... there's an out of the box filter that does EVERYTHING for you... even making a good ETag :) )

提交回复
热议问题