过滤器(登录认证)
登录认证
删除用户信息, 修改用户信息, 查看用户信息, 等操作, 需要登录验证,
这种验证可以使用过滤器统一处理.
Demo: 登录认证
1.定义过滤器
1 public class LoginFilter implements Filter{ 2 @Override 3 public void destroy() { 4 } 5 @Override 6 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 7 throws IOException, ServletException { 8 //向下转型 9 HttpServletRequest req = (HttpServletRequest)request; 10 HttpServletResponse resp = (HttpServletResponse)response; 11 //判断用户是否登录 12 if (req.getSession().getAttribute("username")==null) { 13 //没有登录则跳转到登录页面 14 req.setAttribute("msg", "请登录在修改"); 15 req.getRequestDispatcher("/pages/login.jsp").forward(req, resp); 16 } else { 17 //放行请求 18 chain.doFilter(req, resp); 19 } 20 } 21 @Override 22 public void init(FilterConfig filterConfig) throws ServletException { 23 } 24 }
2.修改配置文件
<!-- 配置过滤器 --> <filter> <filter-name>lgFilter </filter-name> <filter-class>com.sxt.mvcpro.filter.LoginFilter </filter-class> </filter> <filter-mapping> <filter-name>lgFilter </filter-name> <!-- 过滤器处理所有的路径 --> <url-pattern>/emp/delete</url-pattern> <url-pattern>/emp/update</url-pattern> <url-pattern>/emp/list</url-pattern> <url-pattern>/emp_list.jsp</url-pattern> <url-pattern>/dept/list</url-pattern> </filter-mapping>