title: 【学习之路】Filter过滤器
draft: true
tags:

  • 学习之路
  • JavaEE
  • Filter
    categories:
  • JavaEE
  • Filter
    description: ‘Filter学习,理解什么是Filter过滤器和Filter的作用’
    date: 2020-10-27 19:50:22
    cover:

什么是Filter过滤器

  1. Filter过滤器它是JavaWeb的三大组件之一。三大组件分别是Servlet程序、Listener监听器、Filter过滤器
  2. Filter过滤器它是JavaEE的规范。就是接口
  3. Filter过滤器作用是:拦截请求,过滤响应

如何使用Filter

  1. 编写一个类去实现Filter借口
  2. 实现过滤方法doFilter()
  3. 到web.xml中去配置Filter的拦截路径
  • Filter代码
  1. public class TestFilter implements Filter{
  2. //doFilter 方法专门拦截请求,可以做权限检查
  3. public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException{
  4. HttpServletRequest hsr = (HttpServletRequest) servletRequest;
  5. HttpSession session = hsr..getSession();
  6. Object user = session.getAttribute("user");
  7. //如果等于null,说明还没有登录
  8. if (user == null){
  9. servletRequest.getRequestDispatcher("/login.jsp").forward(servletRequest, servletResponse);
  10. return;
  11. }else{
  12. //让程序继续往下访问目标资源
  13. filterChain.doFilter(servletRequest, servletResponse);
  14. }
  15. }
  16. }
  • web.xml代码
  1. <filter>
  2. <filter-name>TestFilter</filter-name>
  3. <filter-class>com.test.filter.TestFilter</filter-class>
  4. </filter>
  5. <filter-mapping>
  6. <filter-name>TestFilter</filter-name>
  7. <url-pattern>/admin/*</url-pattern>
  8. </filter-mapping>
  • loginServlet程序
  1. public class LoginServlet extends HttpServlet {
  2. @Override
  3. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException {
  4. resp.setContentType("text/html; charset=UTF-8");
  5. String username = req.getParameter("username");
  6. String password = req.getParameter("password");
  7. if ("zhangsan".equals(username) && "123456".equals(password)) {
  8. req.getSession().setAttribute("user",username);
  9. resp.getWriter().write("登录 成功!!!");
  10. } else {
  11. req.getRequestDispatcher("/login.jsp").forward(req,resp);
  12. }
  13. }
  14. }
  • login.jsp页面
  1. <form action="http://localhost:8080/15_filter/loginServlet" method="post">
  2. 用户名:<input type="text" name="username"/> <br>
  3. 密 码:<input type="password" name="password"/> <br>
  4. <input type="submit" />
  5. </form>

Filter的生命周期

  • 在web工程启动的时候执行

    • 构造器方法
    • init初始化方法
  • 每次拦截到请求都会执行

    • doFilter过滤方法
  • 停止web工程就会执行

    • destroy销毁

FilterConfig类