Read and understand Filter filter

Keywords: JSP xml Session Java

Filter filter

What is a Filter

1.Filter filter is one of the three components of javaWeb. Servlet program, Listener listener, filter filter
2. It is an interface
3. Function: filter, intercept request, filter response
Application scenario:
1. Authority check
2. Journal operation
3. Business management
...

Use of Filter

Requirement: in a web project, there is a directory named admin. All resources (html pages, jpg pictures, jsp files, etc.) in the directory must be accessed after the user logs in.
Idea: after the user logs in, the user's login information will be saved to the Session domain. Therefore, to check whether the user logs in, you only need to check whether the Session contains the user's login information.
To use the Filter:
1. Write a class to implement the Filter interface
2. Implement the filtering method doFliter()
3. To web.xml Configure the interception path of Fliter in

Filter code:

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println(filterConfig.getFilterName());
        System.out.println(filterConfig.getInitParameter("url"));
    }
    /**
     * dofilter It is specially used to intercept requests, and permission check can be done
     * @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 it is equal to null, it means that you have not logged in yet
        if(user == null){
            servletRequest.getRequestDispatcher("/login.jsp").forward(servletRequest,servletResponse);
            return;
        }else{
            //Let the program continue to access the user's target resources
            filterChain.doFilter(servletRequest,servletResponse);
        }
        //The order in which the filter is executed is by web.xml Executed in the order defined in

    }

web.xml to configure:

    The <! -- Filter tab is used to configure a filter -- >
    <filter>
        <! -- give fi lt er an alias -- >
        <filter-name>AdminFilter</filter-name>
        <! -- full class name of the configuration fi lt er -- >
        <filter-class>com.baidu.filter.AdminFilter</filter-class>
        <init-param>
            <param-name>username</param-name>
            <param-value>root</param-value>
        </init-param>
    </filter>
    
    <! -- configure the interception path of fi lt er -- >
    <filter-mapping>
        <! -- indicates which fi lt er the current interception path is used for -- >
        <filter-name>AdminFilter</filter-name>
        <! -- configure interception path
        /: indicates that the request address is: http://ip:port / Project path mapped to IDEA's web Directory
        /admin/*  :http://ip:port / Project path / Admin/*
        -->
        <url-pattern>/admin/*</url-pattern>
    </filter-mapping>

Full user login:
login.jsp Page (login form):

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
        This is the login page  <br>
        <form action="http://localhost:8080/Filter/loginServlet" method="get">
            user name:<input type="text" name="username"/><br/>
            password:<input type="password" name="password"/><br/>
            <input type="submit"/>
        </form>

</body>
</html>

loginServlet program:

public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset = UTF-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if("whj168".equals(username) &&  "123456".equals(password)){
            req.getSession().setAttribute("user",username);
            resp.getWriter().write("Login, success!!!");
        }else{
            //Jump to login page
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }
    }
}

Filter lifecycle

1. Constructor method
2.init initialization method
3.doFilter filtering method
4. Destroy

FilterConfig class

Every time Tomcat creates a Filter, it creates a FilterConfig class, which contains the configuration information of the Filter configuration file
The FilterConfig class is used to get the configuration content of the filter:
1. Get the contents of Fliter's name filter name
2. Get init param initialization parameters configured in Filter
3. Get the SevletContext object

Java code:

public class AdminFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //Get the name of Filter the content of Filter name
        System.out.println(filterConfig.getFilterName());

        //2. Access web.xml Init param initialization parameter configured in
        System.out.println(filterConfig.getInitParameter("username"));
    }

web.xml:

    <!--filter Label is used to configure a Filter filter-->
    <filter>
        <!--to filter Start an alias-->
        <filter-name>AdminFilter</filter-name>
        <!--to configure filter Full class name of-->
        <filter-class>com.baidu.filter.AdminFilter</filter-class>
        <init-param>
            <param-name>username</param-name>
            <param-value>root</param-value>
        </init-param>
    </filter>

FilterChain filter chain

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

Features of multiple Filter execution:
1. All filter s and target resources are executed in the same thread by default
2. When multiple filters execute together, they all use the same Request object.
FliterChain.doFilter() function of method:
1. Execute the next Filter (if any)
2. Execution target resource (no Filter)

Interception path of Filter

1. Exact match

<url-pattern>/target.jsp<url-pattern>

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

2. Catalog matching

<url-pattern>/admin/*<url-pattern>

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

3. Suffix matching

<url-pattern>*.html<url-pattern>

The path configured above indicates that the request address must end with *. html to be intercepted

<url-pattern>*.do<url-pattern>

The path configured above indicates that the request address must end with *. do to be intercepted

<url-pattern>*.action<url-pattern>

The path configured above indicates that the request address must end with *. action to be intercepted

Filter filter only cares whether the address of the request matches or not, and does not care whether the requested resource exists

Posted by dandaman2007 on Sat, 06 Jun 2020 23:30:08 -0700