我过滤了我的 REST 服务的 BasicAuth 并将用户名存储在 HttpServletRequest
AuthFilter相关代码
public class AuthFilter implements ContainerRequestFilter {
@Context
public transient HttpServletRequest servletRequest;
@Override
public ContainerRequest filter(ContainerRequest containerRequest) throws WebApplicationException {
// all the auth filter actions...
// Set data
servletRequest.setAttribute("auth_username", username);
return containerRequest;
}
}
然后我有一个资源父类(称为 BaseResource,只有一些通用属性)和扩展它的特定类
示例特定类
@Path("/Plant")
public class PlantResource extends BaseResource {
private List<Plant> plantlist = new LinkedList<Plant>();
@GET
@Path("/GetPlantById/plantid/{plantid}")
@Produces("application/json")
public String getPlantById(@PathParam("plantid") String plantid, @Context HttpServletRequest hsr) {
String username = (String)hsr.getAttribute("auth_username");
// do something
}
}
如您所见,我通过“@Context HttpServletRequest hsr”将 HttpServletRequest 处理到函数(如那里所述:Get HttpServletRequest in Jax Rs / Appfuse application?)。这工作正常,我可以正确访问数据!
我现在要做的是在父类的构造函数中访问这个Data,所以我不必在我指定资源的每个函数中都这样做,而是在一个地方
我的尝试:
public class BaseResource {
@Context protected HttpServletRequest hsr; // Also tried private and public:
/* ... */
public BaseResource() {
String username = (String)hsr.getAttribute("auth_username"); // line 96
System.out.println("constructur of BaseResource" + username);
}
}
但这最终会导致:
Aug 05, 2013 3:40:18 PM com.sun.jersey.spi.container.ContainerResponse mapMappableContainerException
Schwerwiegend: The RuntimeException could not be mapped to a response, re-throwing to the HTTP container
java.lang.NullPointerException
at de.unibonn.sdb.mobilehelper.resources.BaseResource.<init>(BaseResource.java:96)
看起来 HttpServletRequest 没有在那里设置。那么如何在父类的构造函数中访问它呢?