我使用JSF 2创建了一个Java Web应用程序。 当用户登录我的应用程序时,我将他的标识符存储在会话中,所以:
FacesContext context = FacesContext.getCurrentInstance();
context.getExternalContext().getSessionMap().put("userid", myBean.getUserId());
然后我创建了我的过滤器:
public class PageFilter implements Filter {
private FilterConfig filterconfig;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.filterconfig = filterconfig;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httprequest =(HttpServletRequest) request;
HttpServletResponse httpresponse =(HttpServletResponse) response;
HttpSession session = ((HttpServletRequest) request).getSession();
String userid = (String) session.getAttribute("userid");
String pageRequested = httprequest.getRequestURI();
try {
if( userid != null && pageRequested.contains("index.xhtml") ) {
System.out.printf("User authenticated with " + httprequest.getRemoteUser() + " username conected.");
httprequest.getRequestDispatcher("/service/home.xhtml").forward(request, response);
} else {
chain.doFilter(request, response);
}
}catch(IOException | ServletException e){
//do something
}
}
@Override
public void destroy() {
System.out.print("Existing from loginFilter");
}
}
我的范围是管理浏览器的刷新按钮,如果用户已经登录,则用户被重定向到/service/home.xhtml。此外,我的Web应用程序中的URL总是:
localhost:8080/myapplication
因此,如果用户在所有页面中浏览网站,则网址始终为该(操作被隐藏)。 问题是如果用户点击浏览器中的url,请求是index.xhtml,我的会话是null(我无法通过session.getAttribute获取用户标识符(" userid");)。 / p>
我的错在哪里? index.xhtml在我的web.xml中定义为welcome-file-list:
<welcome-file-list>
<welcome-file>index.xhtml</welcome-file>
</welcome-file-list>
感谢。