我有一个Stateful Session Bean
保存我的登录会话的 aJSF Session Bean
和一个Servlet Filter
.
我需要做的是阻止非登录用户访问我的页面,所以我做了一个过滤器。
它doFilter()
是这样的:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
String path = req.getRequestURI().substring(req.getContextPath().length());
System.out.println(userManager.isLogged());
if (userManager.isLogged() || path.equals("/") || path.equals("/index.xhtml") || path.startsWith(ResourceHandler.RESOURCE_IDENTIFIER) || path.startsWith("/resources/") || path.startsWith("/admin") || path.equals("/admin/login.xhtml")) {
chain.doFilter(request, response);
} else {
request.getRequestDispatcher("/error.xhtml").forward(request, response);
}
}
在哪里userManager
找到:
private UserManagerLocal lookupUserManagerLocal() {
try {
Context c = new InitialContext();
return (UserManagerLocal) c.lookup("java:global/UNILIFE/UNILIFE-ejb/UserManager!ejb.UserManagerLocal");
} catch (NamingException ne) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
throw new RuntimeException(ne);
}
}
现在,总是System.out.println(userManager.isLogged());
打印为假,而打印为真。#{loginBean.logged}
请注意,这loginBean.logged
只是
public boolean isLogged() {
return userManager.isLogged();
}
并且,在我的托管 Bean 中,userManager
通过
@EJB
private UserManagerLocal userManager;
似乎 servlet 不采用与 JSF 托管 Bean 相同的 SFSB。
我究竟做错了什么?
编辑:新代码
小服务程序
UserManagerLocal userManager = lookupUserManagerLocal();
private UserManagerLocal lookupUserManagerLocal() {
try {
Context c = new InitialContext();
UserManagerLocal userM = (UserManagerLocal) c.lookup("java:global/UNILIFE/UNILIFE-ejb/UserManager!ejb.UserManagerLocal");
HttpServletRequest req = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
req.setAttribute("userManager", userM);
return userM;
} catch (NamingException ne) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
throw new RuntimeException(ne);
}
}
jsf豆
@PostConstruct
public void init(){
HttpServletRequest req = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
userManager = (UserManagerLocal) req.getSession().getAttribute("userManager");
}