是否可以使用JAX-RS设置ETag而无需使用Response对象?

oli*_*ren 12 java etag caching cxf jax-rs

在我发现的关于JAX-RS和缓存的少数几个问题(有答案)中,生成ETag(用于缓存)的答案是在Response对象上设置一些值.如下所示:

@GET
@Path("/person/{id}")
public Response getPerson(@PathParam("id") String name, @Context Request request){
  Person person = _dao.getPerson(name);

  if (person == null) {
    return Response.noContent().build();
  }

  EntityTag eTag = new EntityTag(person.getUUID() + "-" + person.getVersion());

  CacheControl cc = new CacheControl();
  cc.setMaxAge(600);

  ResponseBuilder builder = request.evaluatePreconditions(person.getUpdated(), eTag);

  if (builder == null) {
    builder = Response.ok(person);
  }

  return builder.cacheControl(cc).lastModified(person.getUpdated()).build();
}
Run Code Online (Sandbox Code Playgroud)

问题是对我们不起作用,因为我们对SOAP和REST服务使用相同的方法,通过使用@WebMethod(SOAP),@ GET(以及我们可能需要公开服务的任何其他方法)来注释方法.以前的服务对我们来说是这样的(不包括标题的创建):

@WebMethod
@GET
@Path("/person/{id}")
public Person getPerson(@WebParam(name="id") @PathParam("id") String name){
  return _dao.getPerson(name);
}
Run Code Online (Sandbox Code Playgroud)

有没有办法 - 通过一些额外的配置 - 设置这些标题?这是我第一次发现使用Response对象实际上只比自动转换有一些好处...

我们正在使用Apache CXF.

dli*_*120 7

是的,如果您可以在创建响应对象后生成E-tag,则可以使用拦截器来实现此目的.

public class MyInterceptor extends AbstractPhaseInterceptor<Message> {

    public MyInterceptor () {
        super(Phase.MARSHAL);
    }

    public final void handleMessage(Message message) {
        MultivaluedMap<String, Object> headers = (MetadataMap<String, Object>) message.get(Message.PROTOCOL_HEADERS);

        if (headers == null) {
            headers = new MetadataMap<String, Object>();
        }             

        //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);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果这种方式不可行,我会使用您发布的原始解决方案,只需将您的Person实体添加到构建器:

Person p = _dao.getPerson(name);
return builder.entity(p).cacheControl(cc).lastModified(person.getUpdated()).build();
Run Code Online (Sandbox Code Playgroud)