@Context注入可以用于类,但不能用于对象。
在ContainerRequestFilter中使用HttpServletRequest会产生null指针。
Dropwizard版本:-1.1.0
ContainerRequestFilter
public class ApplicationIPAuthFilter implements ContainerRequestFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationIPAuthFilter.class); private HerculesRestAccessor restAccessor; private String applicationName;
@Context private HttpServletRequest httpServletRequest;
public ApplicationIPAuthFilter(){ }
public ApplicationIPAuthFilter(HerculesRestAccessor accessor, String applicationName) { restAccessor = accessor; this.applicationName = applicationName; }
@Override public void filter(ContainerRequestContext requestContext) throws IOException { // 需要远程Ip String remoteIp = this.httpServletRequest.getRemoteAddr(); .... } }
DynamicFeature
@Provider public class ApplicationIPAuthFeature implements DynamicFeature {
private final HerculesRestAccessor accessor; private final String applicationName;
public ApplicationIPAuthFeature(HerculesRestAccessor accessor, String applicationName) {
this.accessor = accessor; this.applicationName = applicationName; }
@Override public void configure(ResourceInfo resourceInfo, FeatureContext context) { if (resourceInfo.getResourceMethod().getAnnotation(ApplicationIPAuthRequired.class) != null) {
// 不起作用 context.register(new ApplicationIPAuthFilter(accessor, applicationName));
//@Context注入在ContainerRequestFilter中对于类是有效的 //context.register(ApplicationIPAuthFilter.class); } } }
我想在ContainerRequestFilter中获取远程Ip,以基于Ip进行身份验证。
如何解决这个问题.. 需要帮助吗?