简单的Filter,登录界面为/login,如果登录成功,session中带有username。
public class AuthenticationFilter implements Filter { public void init(FilterConfig fConfig) throws ServletException { } public void destroy() { } public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException,ServletException{ HttpSession session = ((HttpServletRequest)request).getSession(false); if(session == null || session.getAttribute("username") == null){ System.out.println("redirect to /login ... "); ((HttpServletResponse)response).sendRedirect("/login"); }else{ System.out.println("username = " + session.getAttribute("username")); chain.doFilter(request, response); } } }