如何在杰克逊自定义批注JsonSerialize类中获取HttpServletRequest

时间:2019-05-20 11:01:46

标签: java rest jackson jersey

我无法使用HttpServletRequest来获取@Context HttpServletRequest httpRequest;,该值即将为空

无法将类注册为提供者,并且它不是球衣资源继承层次结构的一部分

public class EncryptFieldHelper  extends StdSerializer<Object> implements ContextualSerializer{

    @Context
    HttpServletRequest httpRequest;

    private static final long serialVersionUID = 1L;
    private static final String MASKING_PATTERN = "(?=\\w{5})\\w";
    private String value;

    public EncryptFieldHelper(){
        super(Object.class);
    }

    public EncryptFieldHelper(String value){
        super(Object.class);
        this.value = value;
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, 
            BeanProperty property) throws JsonMappingException {

        String annValue = "UNKNOWN";
        EncryptField encryptField = null;
        if (property != null) {
            encryptField = property.getAnnotation(EncryptField.class);
            if (encryptField == null) {
                encryptField = property.getContextAnnotation(EncryptField.class);
            }
        }
        if (encryptField != null) {
            annValue = encryptField.value();
        }
        return new EncryptFieldHelper(annValue);
    }

    @Override
    public void serialize(Object data, JsonGenerator jsonGenerator, 
            SerializerProvider serializerProvider) throws IOException {     
        try {
            if(data instanceof String){
                if(value.equals("mask")){
                    jsonGenerator.writeString(((String)data).replaceAll(MASKING_PATTERN, "*"));
                }
                else{
                    jsonGenerator.writeString("enc_"+Hex.encodeHexString(SymmetricCipherHelper
                            .encrypt((String)data, "AES").getBytes()));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

0 个答案:

没有答案