Parse the Filter of Java Web

Filter What is a filter

1. Filter It is one of the three major components of JavaWeb.
The three major components are:
Servlet program, Listener listener, Filter filter
2, Filter filter It is the specification of JavaEE . That is, interface
3, Filter, its function is to intercept requests (commonly used) and filter responses.
Common application scenarios for intercepting requests are:
1. Permission checking
2. Diary operation
3. Transaction management
...etc.

Simple to use

Requirements :
Under the web project, there is an admin directory. All resources (html pages, jpg images, jsp files, etc.) in this admin directory must be accessed after the user is logged in.

Thinking :
After the user logs in, the user login information will be saved in the Session domain. So to check whether the user is logged in, you can determine whether the Session contains the user's login information.


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
      <%
          Object user = session.getAttribute("user");
          //如果等于null,说明还没有登陆
          if(user==null){
    
    
              request.getRequestDispatcher("/login.jsp").forward(request,response);
              //一般请求转发后,不允许执行任何代码了
              return;
          }
      %>
      我是a.jsp文件
</body>
</html>

Schematic

Before accessing the target resource, check the permissions in the Filter filter
insert image description here
web.xml add

<!--         filter标签用于配置filter过滤器-->
         <filter>
<!--             给filter起一个别名-->
             <filter-name>AdminFilter</filter-name>
<!--             配置filter的全类名-->
             <filter-class>com.test.AdminFilter</filter-class>
         </filter>
<!--    配置filter的拦截路径-->
         <filter-mapping>
<!--             表示当前的拦截路径给哪个filter使用-->
             <filter-name>AdminFilter</filter-name>
<!--             url-pattern配置拦截路径-->
<!--             /表示请求地址为http://ip.port/工程路径/   映射到IDEA的web目录-->
             <url-pattern>/admin/*</url-pattern>
             /表示请求地址为http://ip.port/工程路径/admin/*   -->
         </filter-mapping>

insert image description here
Steps to use the Filter filter:

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

AdminFilter

package com.test;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class AdminFilter implements Filter {
    
    

    public void init(FilterConfig filterConfig) throws ServletException {
    
    
        Filter.super.init(filterConfig);
    }
    //专门用来拦截请求,过滤响应,可以做权限检查
    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");
        //如果等于null,说明还没有登陆
        if(user==null){
    
    
            servletRequest.getRequestDispatcher("/login.jsp").forward(servletRequest,servletResponse);
            //一般请求转发后,不允许执行任何代码了
            return;
        }else{
    
    
            //让程序继续往下访问用户的目标资源
            FilterChain.doFilter(servletRequest,servletResponse);
        }

    }

    public void destroy() {
    
    
        Filter.super.destroy();
    }
}

Loginservlet

package com.testservlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        resp.setContentType("text/html;charset=UTF-8");
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        if("ddd".equals(name)&&"123456".equals(password)){
    
    
            req.getSession().setAttribute("user",name);
            resp.getWriter().write("登陆成功");
        }else{
    
    
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }
    }
}

jpg pictures may be displayed because there is a cache, just clear the cache, or add request parameters
http://localhost:8080/15_Filter/admin/a.html?

Filter life cycle

The life cycle of Filter contains several methods

1. Constructor method
2. Init initialization method
Steps 1 and 2 are executed 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
4. destroy
Step 4, when the web project is stopped, it will be executed (stop the web project and also destroy the Filter filter)

FilterConfig class

As the name suggests, the FilterConfig class is the configuration file class of the Filter filter.
Every time Tomcat creates a Filter, it also creates a FilterConfig class, which contains the configuration information of the Filter configuration file.

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

1. Get the content of the filter name filter-name (the name configured in web.xml)

2. Get the init-param initialization parameters configured in Filter

<filter>
<!--             给filter起一个别名-->
             <filter-name>AdminFilter</filter-name>
<!--             配置filter的全类名-->
             <filter-class>com.test.AdminFilter</filter-class>
             <init-param>
                 <param-name>username</param-name>
                 <param-value>root</param-value>
             </init-param>
             <init-param>
                 <param-name>url</param-name>
                 <param-value>jdbc:mysql://localhost3306/test</param-value>
             </init-param>
         </filter>

3. Get the ServletContext object
insert image description here

 public void init(FilterConfig filterConfig) throws ServletException {
    
    
        // 1、获取 Filter 的名称 filter-name 的内容
        System.out.println("filtername的值是:"+filterConfig.getFilterName());
        // 2、获取在 web.xml 中配置的 init-param 初始化参数
        System.out.println("初始化参数username的值是:"+filterConfig.getInitParameter("username"));
        System.out.println("初始化参数url的值是:"+filterConfig.getInitParameter("url"));
        // 3、获取 ServletContext 对象
        System.out.println("获取Servlet对象:"+filterConfig.getServletContext());

    }

FilterChain filter chain

Filter filter
Chain chain, the chain
FilterChain is the filter chain (how multiple filters work together)
insert image description here
The role of the FilterChain.doFilter method

1. Execute the next Filter (if any)
2. Execute the target resource (without Filter)

When multiple Filter filters are executed, their execution order is determined by the order in which they are configured in web.xml from top to bottom

Features of multiple Filter filter implementations :

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

   public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    
    
        
        System.out.println("前置代码");
        filterChain.doFilter(servletRequest,servletResponse);
        System.out.println("后置代码");
        
    }

If the doFilter and post of Filter2 are not executed, then the execution order is
Filter1 pre->Filter1doFilter->Filter2 pre->Filter1 post

If doFilter is executed, the postcode is executed, otherwise it is not executed

Filter's interception path

exact match

<url-pattern>/target.jsp</url-pattern>
The path configured above means that the request address must be:
http://ip:port/project path/target.jsp

directory match

<url-pattern>/admin/*</url-pattern>
The path configured above means that the request address must be: http://ip:port/project path/admin/ *

suffix matching

The path configured above <url-pattern>*.html</url-pattern>
means that the request address must end with .html to intercept the path configured above
<url-pattern>*.do</url-pattern>
. Indicates that the request address must end with .do to intercept the path configured above
<url-pattern>*.action</url-pattern>
, indicating that the request address must end with .action to intercept the Filter

The filter only cares whether the requested address matches, not whether the requested resource exists! ! !

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324115987&siteId=291194637