过滤器Filter

过滤器实际上就是对web资源进行拦截,做一些处理后再交给下一个过滤器或servlet处理
通常都是用来拦截request进行处理的,也可以对返回的response进行拦截处理
应用场景:自动登录、统一设置编码格式、访问权限控制、敏感字符过滤等

过滤器

样例

模拟在登录页面(login.html)进行登录,使用过滤器(FilterDemo.java)进行拦截,如果session中存在登录用户信息,则直接跳转主页(index.html),否则转发到登录页面(login.html)
login.html



  
    
    Insert title here
  
  
    
用户名:
密码:

index.html



  
    
    Insert title here
  
  
    我是主页
  

LoginFilter.java

public class FilterDemo implements Filter {

    /*初始化方法*/
    public void init(FilterConfig fConfig) throws ServletException {
    }

    /*过滤方法*/
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("开始过滤了");
        HttpServletRequest hsRequest=(HttpServletRequest) request;
        HttpSession session = hsRequest.getSession();
        String username=(String) session.getAttribute("username");
        if("zhangsan".equals(username)) {
            chain.doFilter(request, response);//放行
        }else {
            request.getRequestDispatcher("login.html").forward(hsRequest, response);
        }
    }

    /*销毁*/
    public void destroy() {
    }
}

LoginServlet.java

public class LoginServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*用户名 zhangsan  密码123456*/
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(username+password);
        HttpSession session = request.getSession();
        if("zhangsan".equals(username)&&"123456".equals(password)) {
            session.setAttribute("username", username);
            System.out.println("用户名密码正确!");
            /*跳转页面*/
            response.sendRedirect("index.html");
        }
    }
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

web.xml


  ...
  
    
    loginServlet
    loginServlet
    xxx.LoginServlet
  
  
    loginServlet
    /loginServlet
  
  ...
  ...
  
    filterDemo
    xxx.FilterDemo
  
  
    filterDemo
    /index.html
  
  ...

你可能感兴趣的:(过滤器Filter)