Filter (super detailed)

Posted by reddevil on Sat, 26 Feb 2022 07:10:57 +0100

Statement: This article is the notes sorted out according to the blogger's learning content. It is only used for exchange learning. If you need to watch the video, please move to: http://www.atguigu.com/

1.Filter ? What is a filter

  1. Filter filter is one of the three major components of Java Web.
    The three components are: Servlet program, Listener listener and Filter filter
  2. Filter filter, which is the specification of Java EE. That is, the interface
  3. Filter filter is used to intercept requests and filter responses.

Common application scenarios for intercepting requests include:
1. Permission check 2 Journal operation 3 Transaction management... Etc

2. Initial experience of filter

Requirement: under your web project, there is an admin directory. All resources in the admin directory (html pages, jpg images, jsp files, etc.) must be accessed after the user logs in.

Thinking: Based on what we have learned before. We know that after logging in, users will save the login information to the Session domain. Therefore, to check whether the user logs in, you can judge whether the Session contains the user login information, and then!!!

a.jsp:

<body>
    <%
        Object user = session.getAttribute("user");
        // If user = null; That means user hasn't logged in yet
        if (user == null) {
            request.getRequestDispatcher("/login.jsp").forward(request,response);
            return;     // Generally, after the request is forwarded, no code is allowed to be executed. Here you can directly return
        }
    %>
    I am a.jsp file
</body>

But what should I write in html pages? Filter is required

Workflow diagram of Filter:

Use steps of Filter:

1. Write a class to implement the Filter interface
2. Implement the filtering method doFilter()
3. Go to the web Configure the interception path of Filter in XML

AdminFilter. Java (inheriting the Filter class):

/**
 * doFilter Method, which is specially used to intercept requests and check permissions
 * @param servletRequest
 * @param servletResponse
 * @param filterChain
 * @throws IOException
 * @throws ServletException
 */
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
    HttpSession session = httpServletRequest.getSession();
    Object user = session.getAttribute("user");
    // If user = null; That means user hasn't logged in yet
    if (user == null) {
        httpServletRequest.getRequestDispatcher("/login.jsp").forward(httpServletRequest,servletResponse);
        return;     // Generally, after the request is forwarded, no code is allowed to be executed. Here you can directly return
    } else {
        // Let the program continue to access the user's target resources
        filterChain.doFilter(servletRequest,servletResponse);
    }
}

At this time, you have permission to check the code, but you don't know where to check. At this time, you need to go to xml configuration to check what.

<!--filter Label is used to configure a Filter filter-->
<filter>
    <!--to filter Create an alias-->
    <filter-name>Adminfilter</filter-name>
    <!--to configure filter Full class name-->
    <filter-class>com.filter.AdminFilter</filter-class>
</filter>
<!--to configure filter Interception path of filter-->
<filter-mapping>
    <!--Indicates to which of the current interception paths filter Filter use-->
    <filter-name>Adminfilter</filter-name>
    <!--Configure interception path
    / Indicates that the request address is: http://ip:port / Project path / web Directory mapped to IDEA
    /admin/* Indicates that the request address is http://ip:port / Project path / admin / * (all under admin)
    -->
    <url-pattern>/admin/*</url-pattern>
</filter-mapping>

Complete user login and permission check:

login.jsp:

<body>
    This is the landing page: login.jsp page <br>
    <form action="http://localhost:8080/15_filter/loginServlet" method="get">
        user name:<input type="text" name="username"/> <br>
        password:<input type="password" name="password"/> <br>
        <input type="submit" />
    </form>
</body>

LoginServlet.java:

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("text/html; charset=UTF-8");    //Resolve response garbled code

    String username = req.getParameter("username");
    String password = req.getParameter("password");
    if ("wzg168".equals(username) && "123456".equals(password)) {
        req.getSession().setAttribute("user",username);
        resp.getWriter().write("Login succeeded!!!");
    } else {
        req.getRequestDispatcher("/login.jsp").forward(req,resp);
    }
}

3.Filter life cycle

The life cycle of Filter contains several methods

  1. Constructor method

  2. init initialization method
    Step 1 and 2: execute when the web project starts (Filter has been created)

  3. doFilter filtering method
    Step 3: every time a request is intercepted, it will be executed (visit the a.jsp page under the admin directory, visit once, and intercept a request)

  4. Destroy destroy
    Step 4: when the web project is stopped, it will be executed (stop the web project and destroy the Filter)

4.FilterConfig class

The FilterConfig class, as its name implies, is the configuration file class of Filter filter.
Every time Tomcat creates a Filter, it will also create a FilterConfig class, which contains the configuration information of the Filter configuration file.

The function of FilterConfig class is to obtain the configuration content of filter filter

  1. Get the name of Filter and the content of Filter name

  2. Get Wen. In Filter Init param initialization parameter of XML configuration

  3. Get ServletContext object

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("2.Filter Initialization method init(FilterConfig filterConfig)");
    

    // 1. Get the name of Filter and the content of Filter name (the name configured in Web XML)
    System.out.println("filter-name:" + filterConfig.getFilterName());
    // 2. Get on the web Init param initialization parameters configured in XML
    System.out.println("the value of initialization parameter username is:" + filterConfig.getInitParameter("username"));
    System.out.println("the value of initialization parameter url is:" + filterConfig.getInitParameter("url"));
    // 3. Get ServletContext object
    System.out.println(filterConfig.getServletContext());

    }
    

5.FilterChain filter chain

Filter filter
Chain chain
FilterChain is the filter chain (how multiple filters work together)

FilterChain. The function of dofilter() method:

1. Execute the next Filter (if any)
2. Implementation target resources

Implementation details of Filter:

Filter1.java:

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    System.out.println("Filter1 Pre code");
    filterChain.doFilter(servletRequest,servletResponse);
    System.out.println("Filter1 Post code");
}

Filter2.java:

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    System.out.println("Filter2 Pre code");
    filterChain.doFilter(servletRequest,servletResponse);
    System.out.println("Filter2 Post code");
}

target.jsp:

<body>
    <%
        System.out.println("target.jsp Page executed");
    %>
</body>

web.xml:

<filter>
    <filter-name>Filter1</filter-name>
    <filter-class>com.filter.Filter1</filter-class>
</filter>
<filter-mapping>
    <filter-name>Filter1</filter-name>
    <url-pattern>/target.jsp</url-pattern>
</filter-mapping>
<filter>
    <filter-name>Filter2</filter-name>
    <filter-class>com.filter.Filter2</filter-class>
</filter>
<filter-mapping>
    <filter-name>Filter2</filter-name>
    <url-pattern>/target.jsp</url-pattern>
</filter-mapping>

Access target jsp:

The execution order can be seen.

In addition, if Filter2 is placed on Filter1 in xml, Filter2 will be executed first, and then Filter1 will be executed. In other words, when multiple filter filters are executed, their priority is determined by them on the web The order of top-down configuration in xml is determined!

Supplement:
Features of multiple Filter execution:

  1. All filter and target resources are executed in the same thread by default
  2. When multiple Filter filters are executed at the same time, they all use the same Request object

Supplement 1 Demo: filterchain in Filter1 and Filter2 doFilter(servletRequest,servletResponse); Use thread before and after currentThread(). Getname() gets the thread name and target Thread. JSP page is also used currentThread(). Getname() gets the thread name, and the running result displays:

visit: http://localhost:8080/15_filter/target.jsp
The results show that the threads are the same.

Supplement 2 demonstration: filterchain in Filter1 and Filter2 doFilter(servletRequest,servletResponse); ServletRequest is used before and after Getparameter ("username") gets the name and target of the request object JSP using request Getparameter ("username") gets the name of the request object, and the running result shows:

visit: http://localhost:8080/15_filter/target.jspusername=12345
The result shows that the request object is the same.

6. Interception path of filter

– exact match

<filter-mapping>
    <filter-name>Filter2</filter-name>
    <url-pattern>/target.jsp</url-pattern>  <!--Exact match-->
</filter-mapping>

The path configured above indicates that the request address must be: http://ip:port/ Project path / target jsp

– directory matching

<filter-mapping>
    <filter-name>Adminfilter</filter-name>
    <url-pattern>/admin/*</url-pattern> <!--Directory matching-->
</filter-mapping>

The path configured above indicates that the request address must be: http://ip:port/ Project path / admin/*

– suffix matching

<filter-mapping>
    <filter-name>Filter2</filter-name>
    <url-pattern>*.html</url-pattern>  <!--Suffix matching-->
</filter-mapping>

The path configured above indicates that the request address must be in The end of html will be intercepted

<filter-mapping>
    <filter-name>Filter2</filter-name>
    <url-pattern>*.do</url-pattern>  <!--Suffix matching-->
</filter-mapping>

The path configured above indicates that the request address must be in It will be intercepted at the end of do

<filter-mapping>
    <filter-name>Filter2</filter-name>
    <url-pattern>*.action</url-pattern>  <!--Suffix matching-->
</filter-mapping>

The path configured above indicates that the request address must be in It will be intercepted at the end of action

<filter-name>Filter2</filter-name>
<url-pattern>*.do</url-pattern>  <!--Suffix matching-->

```

The path configured above indicates that the request address must be in It will be intercepted at the end of do

<filter-mapping>
    <filter-name>Filter2</filter-name>
    <url-pattern>*.action</url-pattern>  <!--Suffix matching-->
</filter-mapping>

The path configured above indicates that the request address must be in It will be intercepted at the end of action

Filter filter only cares about whether the requested address matches, not whether the requested resource exists (only depends on whether the suffix is equal to, not whether the suffix really exists in reality)!!!

Topics: Java Front-end JavaEE html Interview