拦截非法登录
仅需一个类
@WebFilter(urlPatterns = {"/**"}) public class myfilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException, IOException { HttpServletRequest httpServletRequest=(HttpServletRequest) servletRequest; System.out.println(httpServletRequest.getRequestURI()); if(httpServletRequest.getRequestURI().equals("/stu/login")){ filterChain.doFilter(servletRequest,servletResponse); System.out.println("合法请求"); } Object user = httpServletRequest.getSession().getAttribute("user"); if(user==null){ System.out.println("非法请求"); httpServletRequest.getRequestDispatcher("/jsp/login.jsp").forward(servletRequest,servletResponse); }else{ filterChain.doFilter(servletRequest,servletResponse); } } @Override public void destroy() { } }