package com.aaa.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; import javax.servlet.http.HttpSession; /** * 一、创建一个filter类 * 1. 就是普通的java类 实现filter * 2.filter 配置 * <filter> * <filter-name>filter的类名</filter-name> * <filter-class>com.aaa.filter.FilterDemo.filter的类名</filter-class> 这里是相对路径 你自己定义的包名+filter类名 * </filter> * <filter-mapping> * <filter-name>filter的类名</filter-name> <url-pattern> /* </url-pattern> URL在这里设置 需要拦截的路径 /* 是拦截所有! * </filter-mapping> * * * requesturi.contains("login.jsp") * contanis 的包含判断 * 如果前面的字符串包含后边的login 就返回true 放行 * 否则就返回false 拦截 */ public class LanJieDemo implements Filter { public LanJieDemo() { } public void destroy() { // TODO Auto-generated method stub } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { /* *filter 过滤器 放行 和拦截 * getSession 是servletRequest 子类的方法需要先进行类型转换,才能使用。 * 使用之前先判断 */ HttpServletRequest req=(HttpServletRequest)request; HttpServletResponse reps=(HttpServletResponse)response; HttpSession session = req.getSession(); Object user = session.getAttribute("u"); if (user!=null) { chain.doFilter(req, reps); }else { //将不需要拦截的资源配置 添加到string数组中 String [] arr= {"login.jsp","UserLoginServlet","register","Register","logout.jsp","Logout"}; //通过req.getrequesturl 获得本次请求的地址 String requestURI = req.getRequestURI(); //定义 Boolean类型变量tag = false boolean tag=false; //foreach 便利我们定义的string数组 里面都是不需要拦截的资源 for (String str : arr) { //如果本次请求的地址在 string数组中 就将tag=true if (requestURI.contains(str)) { tag=true; break; //结束循环! } } //true 就放行 if (tag) { chain.doFilter(req, reps); }else { //进行拦截 回到登录界面! reps.sendRedirect("login.jsp"); } }