Why is an injected value sometimes null inside my custom ConstraintValidator?

痞子三分冷 提交于 2020-01-06 13:27:17

问题


i created a custom ConstraintValidator Annotation which called APIAuth, and i tried to fetch the remote user IP Address Using @Context HttpServletRequest , but the problem is when calling the APIAuth inside my Stateless , the APIAuth custom validator work , and it fetch the remote user ip address , but when i try to refresh the request again quickly , it throw an exception , because of @Context HttpServletRequest be null at this case , it need from me to wait some seconds before trying to request the Stateless Restful again .

my APIAuth Code :

APIAuth.class

@Documented
@Constraint(validatedBy = APIAuthValidator.class)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface APIAuth {
    String message() default "";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

APIAuthValidator.class

public class APIAuthValidator implements ConstraintValidator<APIAuth, String> {

@Context
private HttpServletRequest client;

@Override
public void initialize(APIAuth constraintAnnotation) {
}

@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
    boolean valid = "127.0.0.1".equals(client.getRemoteAddr());

    return valid;
}

Note: i noticed also that when i define the remote user ip address at first inside the initialize() constructor , then it cache the value and didn't update it else after some of seconds , although of refreshing requesting of Restful Stateless API class which contain the calling of my custom annotation many times.

Thank you,

来源:https://stackoverflow.com/questions/21368583/why-is-an-injected-value-sometimes-null-inside-my-custom-constraintvalidator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!