为了保护信息安全,防止直接访问信息页,需要验证用户是否登陆。思路为,先过滤掉登陆功能所包含资源的路径,在访问其他资源时判断用户是否登陆——判断 Session 中是否包含User。有的话放行,没有的话跳转到登陆页。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| @WebFilter("/*") public class LoginFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException { HttpServletRequest request = (HttpServletRequest) req; String uri = request.getRequestURI(); if(uri.contains("/login.jsp") || uri.contains("/loginServlet") || uri.contains("/js/") || uri.contains("/css/") || uri.contains("/fonts/") || uri.contains("/checkCodeServlet")){ chain.doFilter(req, resp); }else { Object user = request.getSession().getAttribute("user"); if (user != null){ chain.doFilter(req, resp); }else { request.setAttribute("login_msg","您尚未登陆,请登录"); request.getRequestDispatcher("/login.jsp").forward(request,resp); } } }
public void init(FilterConfig config) throws ServletException {
}
public void destroy() { }
}
|