在Jersey 2.0中注入HttpServletRequest对象时,我得到了这个例外 - > java.lang.IllegalStateException: Not inside a request scope
。
我尝试在AuthenticationFIlter中注入HttpServletRequest对象以获取客户端IP地址,但是由于上述异常而失败了,但是相同的代码完全适用于jersey 2.2.3 api。
import javax.annotation.Priority;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Priorities;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.Provider;
@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthFilter implements ContainerRequestFilter {
@Context
HttpServletRequest request;
public String getClientIP(@Context HttpServletRequest request) {
return request.getRemoteAddr();
}
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
System.out.println("Filter called.");
clientIP = new AuthFilter().getClientIP(request);
}
}
答案 0 :(得分:1)
你的问题有点令人困惑。您提到您使用的是 Jersey 2.x ,但实际上您正在使用 Jersey 1.x API。
Jersey 1.x 和 Jersey 2.x 使用不同的包名称:
com.sun.jersey
org.glassfish.jersey
在Jersey 2.x中,您将拥有以下内容:
import java.io.IOException;
import javax.annotation.Priority;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Context;
import javax.ws.rs.ext.Provider;
@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter {
@Context
private HttpServletRequest request;
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
String remoteAddress = request.getRemoteAddr();
...
}
}
ContainerRequestFilter
接口位于javax.ws.rs.container
包中,它是JAX-RS 2.0 API的一部分。而Jersey 2.x是JAX-RS 2.0规范的参考实现。