在Jersey 1.x中,我们从(Jersey)会话属性访问了Wicket会话,如https://*.com/a/15767824/1399659所述.
在转向Jersey 2.x时,似乎使用ContainerRequestFilter的正确模式,也允许Spring bean注入.我们成功地通过包括这项工作
<param-name>jersey.config.server.provider.packages</param-name>
作为ServletContainer的init-param并在ContainerRequestFilter实现上使用@Provider批注.但是这个容器过滤器是一个单例,并且不可能将HttpServletRequest注入其中(参见JERSEY-2114)
在filter()方法中,我们可以访问ContainerRequestContext,但无法从那里访问HttpServletRequest.
那么有没有办法:
>在servlet过滤器中启用Spring bean注入(也使用Jersey)?
>从ContainerRequestFilter中访问servlet请求?
>以其他方式从具有泽西过滤能力的Spring-bean感知对象访问wicket会话?
`
import java.io.IOException;
import javax.servlet.http.HttpSession;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.Provider;
import org.apache.wicket.injection.Injector;
@Provider
public class SecurityContextFilter implements ContainerRequestFilter {
//@Context
//HttpServletRequest webRequest;
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
//HttpSession httpSession = webRequest.getSession();
//MyWicketSession mySession = (MyWicketSession) httpSession.getAttribute("wicket:" + BaseConstants.WICKET_FILTER_NAME + ":session");
//doAuthCheck(mySession, requestContext);
}
...
}
`
提前致谢
解决方法:
泽西岛的Fixed:
import javax.annotation.Priority;
import javax.ws.rs.Priorities;
@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthRequestFilter implements ContainerRequestFilter {
@Context
HttpServletRequest webRequest;
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
final HttpSession session = webRequest.getSession();
requestContext.setSecurityContext(new SecurityContext() {
@Override
public Principal getUserPrincipal() {
return new PrincipalImpl((String)session.getAttribute("USER_NAME"));
}
@Override
public boolean isUserInRole(String s) {
return false;
}
@Override
public boolean isSecure() {
return false;
}
@Override
public String getAuthenticationScheme() {
return null;
}
});
}
}
您也可以在不使用@Provider注释的情况下注册过滤器:
import org.glassfish.jersey.server.ResourceConfig;
import javax.ws.rs.ApplicationPath;
/**
* Root REST resource class.
*/
@ApplicationPath("/rest")
public class RootResource extends ResourceConfig {
/**
* Initializes all resources from REST package.
*/
public RootResource() {
packages("com.example.rest");
register(AuthRequestFilter.class);
}
}
注意:Glassfish 4.0.0使用旧的Jersey 2.0.
你将不得不使用these tips升级泽西岛(它没有被证明效果很好).或者更好的方法是下载nightly build of Glassfish 4.0.1.,但目前还不完全稳定.我希望新版本即将发布.