所以我正在编写一个拦截器,所以当用户尝试访问一个没有被登录的页面时,他会被发送回登录。事情是我的过滤器是检查用户是否登录的条件总是正确的,最糟糕的是;它还拦截资源(css、图像、js)那么我应该如何更改我的过滤器才能正常工作?这是我的代码:
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
try {
// check whether session variable is set
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
boolean estaLoggeado = false;
if (req.getSession().getAttribute("estaLoggeado") != null) {
estaLoggeado = new Boolean("" + req.getSession().getAttribute("estaLoggeado"));
}
// allow user to proccede if url is login.xhtml or user logged in or user is accessing any page in //public folder
String reqURI = req.getRequestURI();
System.out.println(reqURI);
System.out.println("index: " + reqURI.indexOf("/index.xhtml"));
System.out.println("pages: " + reqURI.indexOf("/pages/"));
System.out.println("resources: " + reqURI.contains("javax.faces.resource"));
System.out.println("log: " + estaLoggeado);
if ((reqURI.indexOf("/index.xhtml") >= 0 || reqURI.indexOf("/pages/") >= 0 || reqURI.contains("javax.faces.resource"))) {
System.out.println("Si");
chain.doFilter(request, response);
} else { // user didn't log in but asking for a page that is not allowed so take user to login page
System.out.println("No");
res.sendRedirect(req.getContextPath() + "/pages/index.xhtml"); // Anonymous user. Redirect to login page
}
} catch(Throwable t) {
System.out.println(t.getMessage());
}
} //doFilter
提前致谢!!