servlet的过滤器解决了是否登录状态问题。
1.创建一个AccessFilter类,基础代码
package valid.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class AccessFilter implements Filter{ public void destroy() { System.out.println("请求销毁"); } @Override public void doFilter(ServletRequest res, ServletResponse rep, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) res; HttpServletResponse response = (HttpServletResponse) rep; String requestURI = request.getRequestURI(); String path = request.getContextPath(); //如果请求路径等于首页ctl if(requestURI.startsWith(path + "/servlet/valServlet")){ chain.doFilter(res, rep); } else{ //这个时候,就说明需要判断权限了 Object user = request.getSession().getAttribute("login"); if(null == user){ response.sendRedirect("../index.jsp"); }else{ chain.doFilter(res, rep); } } //放行 } public void init(FilterConfig arg0) throws ServletException { System.out.println("请求初始化"); } }
2.web.xml配置
<filter> <filter-name>acess</filter-name> <filter-class>valid.filter.AccessFilter</filter-class> </filter> <filter-mapping> <filter-name>acess</filter-name> <url-pattern>/servlet/*</url-pattern> </filter-mapping>
所有servlet请求,都会先经过AccessFilter,只要没有登录状态,都将会被拦截,并跳转到首页