JAVA WEB篇4——Filter、Listener

JAVA WEB篇4——Filter、Listener

1、Filter

  • Filter本意为”过滤“的含义,是JavaWeb的三大组件之一,三大组件为:Servlet、Filter、 Listener
  • 过滤器是向 Web 应用程序的请求和响应处理添加功能的 Web 服务组件
  • 过滤器相当于浏览器与Web资源之间的一道过滤网,在访问资源之前通过一系列的过滤器对请求 进行修改、判断以及拦截等,也可以对响应进行修改、判断以及拦截等

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-3FHACccm-1626698849119)(C:\Users\yoya\AppData\Roaming\Typora\typora-user-images\image-20210719193135266.png)]

1.1、简单的登录案例

<%--
  Created by IntelliJ IDEA.
  User: yoya
  Date: 2021/7/18
  Time: 10:36
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  <form action="${pageContext.request.contextPath}/RuoyrServlet">
    <input type="text" name="pwd">
    <input type="submit" value="提交">
  </form>
  </body>
</html>
@WebServlet("/RuoyrServlet")
public class RuoyrServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("22222222222222222222222");
        String pwd = request.getParameter("pwd");
        request.getSession().setAttribute("pwd",pwd);
        if (pwd.equalsIgnoreCase("123"))
        response.sendRedirect(request.getContextPath()+"/success.jsp");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
<%--
  Created by IntelliJ IDEA.
  User: yoya
  Date: 2021/7/19
  Time: 19:41
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%
    if (session.getAttribute("pwd")==null)
        response.sendRedirect(request.getContextPath()+"/index.jsp");
%>
<h1>登陆成功</h1>
</body>
</html>

每次都在jsp里写判断有点麻烦

1.2、Filter使用方式

如果有多个过滤器都满足过滤的条件,则容器依据映射的先后顺序来调用各个过滤器

1.2.1、web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <filter>
        <filter-name>RuoyeFilter</filter-name>
        <filter-class>RuoyeFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>RuoyeFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>
@WebFilter(urlPatterns = { "/*" })
public class RuoyeFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("11111111111111111");
        //放行
        HttpServletRequest httpServletRequest= (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse= (HttpServletResponse) servletResponse;
        System.out.println(httpServletRequest.getServletPath());
        if (httpServletRequest.getSession().getAttribute("pwd")!=null||httpServletRequest.getServletPath().equals("/RuoyrServlet")||httpServletRequest.getServletPath().equals("/index.jsp"))
            filterChain.doFilter(servletRequest,servletResponse);
        else
            httpServletResponse.sendRedirect(httpServletRequest.getContextPath());
        System.out.println("3333333333333333333333");
    }
}

**注意导的包 import javax.servlet.annotation.WebFilter; **

1.2.2、@WebFilter

@WebFilter(urlPatterns = { "/*" })
public class RuoyeFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("11111111111111111");
        //放行
        HttpServletRequest httpServletRequest= (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse= (HttpServletResponse) servletResponse;
        System.out.println(httpServletRequest.getServletPath());
        if (httpServletRequest.getSession().getAttribute("pwd")!=null||httpServletRequest.getServletPath().equals("/RuoyrServlet")||httpServletRequest.getServletPath().equals("/index.jsp"))
            filterChain.doFilter(servletRequest,servletResponse);
        else
            httpServletResponse.sendRedirect(httpServletRequest.getContextPath());
        System.out.println("3333333333333333333333");
    }
}

1.3、多过滤器

JAVA WEB篇4——Filter、Listener

1.4、过滤器的优点

  • 实现代码的“可插拔性”,即增加或减少某个功能模块,不会影响程序的正常执行
  • 可以将多个相同处理逻辑的模块集中写在过滤器里面,可实现重复利用、也方便代码的维护

2、 Listener

用来监听Servlet容器产生的事件并进行相应的处理

这玩意很强,但是没看出来有什么用,待补

上一篇:php微信公众号开发之答题连闯三关


下一篇:HttpServletRequest getRequestURL和 getRequestURI等地址的区别