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

前端 未结 3 482
心在旅途
心在旅途 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:49

    Yes you might be able to use interceptors to achieve this if you could generate the E-tag AFTER you create your response object.

    public class MyInterceptor extends AbstractPhaseInterceptor {
    
        public MyInterceptor () {
            super(Phase.MARSHAL);
        }
    
        public final void handleMessage(Message message) {
            MultivaluedMap headers = (MetadataMap) message.get(Message.PROTOCOL_HEADERS);
    
            if (headers == null) {
                headers = new MetadataMap();
            }             
    
            //generate E-tag here
            String etag = getEtag();
            // 
            String cc = 600;
    
            headers.add("E-Tag", etag);
            headers.add("Cache-Control", cc);
            message.put(Message.PROTOCOL_HEADERS, headers);
        }
    }
    

    If that way isn't viable, I would use the original solution that you posted, and just add your Person entity to the builder:

    Person p = _dao.getPerson(name);
    return builder.entity(p).cacheControl(cc).lastModified(person.getUpdated()).build();
    

提交回复
热议问题