且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

泽西岛更新实体属性MessageBodyWriter

更新时间:2023-02-13 12:18:18

MessageBodyWriter不需要执行逻辑来操纵实体.它的职责只是编组/序列化.

The MessageBodyWriter shouldn't need to perform an logic to manipulate entities. It's responsibility is simply to marshal/serialize.

您正在寻找的是 WriterIntercptor 的目的是精确执行您要尝试执行的操作,它会在序列化之前操纵该实体.

What you are looking for instead is an WriterIntercptor, whose purpose is to do exactly what you are trying to do, manipulate the entity before being serialized.

在泽西文件"中有关于解释的全部解释href ="https://jersey.java.net/documentation/latest/filters-and-interceptors.html#d0e9678" rel ="nofollow">此处

这是一个例子

@Provider
public class MyDTOWriterInterceptor implements WriterInterceptor {

    @Override
    public void aroundWriteTo(WriterInterceptorContext context) 
            throws IOException, WebApplicationException {
        Object entity = context.getEntity();
        if (entity instanceof MyDTO) {
            ((MyDTO)entity).setDescription("Some Description");
        }
        context.proceed();
    }  
}

您可以添加注释,以便仅某些资源方法/类使用此拦截器,例如

You can add annotation so only certain resource methods/classes use this interceptor, e.g.

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.ws.rs.NameBinding;

@NameBinding
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface AddDescription {

}
...

@AddDescription
@Provider
public class MyDTOWriterInterceptor implements WriterInterceptor {
...

@Path("dto")
public class MyDTOResource {

    @GET
    @AddDescription
    @Produces(MediaType.APPLICATION_JSON)
    public Response getDto() {
        return Response.ok(new MyDTO()).build();
    }
}

如果由于某种原因您不能更改类(也许这就是为什么要在这里设置描述(谁知道)的原因),则可以使用

If for some reason you can't alter the class (maybe that's why you need to set the description here, who's knows), then you can use Dynamic Binding, where you don't need to to use annotations. You can simple do some reflection to check the method or class. The link has an example.