JavaWeb listener listener, Filter

Note sorting comes from Shang Silicon Valley , for my review only, no other purpose

1, Listener listener

1. What is a Listener listener?

(1) Listener listener, which is one of the three major components of Java Web. The three major components of Java Web are Servlet program, Filter filter and listener listener.
(2) Listener, which is the specification of Java EE, is the interface
(3) The function of a listener is to monitor the change of something. Then through the callback function, feedback to the customer (program) to do some corresponding processing.

2.ServletContextListener listener

(1)ServletContextListener, which can listen to the creation and destruction of ServletContext objects.

(2) The ServletContext object is created when the web project starts and destroyed when the web project stops

(3) After listening to creation and destruction, the method feedback of ServletContextListener listener will be called respectively.

(4) How do I use the ServletContextListener listener to listen for ServletContext objects?
① Write a class to implement ServletContextListener
② Implement its two callback methods

public class MyServletContextListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("Servlet Object was created");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("Servlet The object was destroyed");
    }
}

③ , to the web Configuring listeners in XML

    <servlet>
        <servlet-name>MyServletContextListener</servlet-name>
        <servlet-class>servletContextListener.MyServletContextListener</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>MyServletContextListener</servlet-name>
        <url-pattern>/loginServlet</url-pattern>
    </servlet-mapping>


<!--  Configure listener  -->
    <listener>
        <listener-class>servletContextListener.MyServletContextListener</listener-class>
    </listener>

2, Filter filter

1.Filter what is a filter

(1) Filter is one of the three major components of Java Web. The three components are: Servlet program, Listener listener and filter filter
(2) Filter, which is the specification of Java EE. That is, the interface
(3) Filter is used to intercept requests and filter responses.
(4) Common application scenarios for intercepting requests include:
Permission check, journal operation, transaction management, etc

2. Basic usage example of filter

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

Thinking: Based on what we have learned before. We know that after a user logs in, the user login information will be saved to the Session domain. Therefore, to check whether the user logs in, you can judge whether the Session contains the user login information|


Test code

public class AdminFilter implements Filter {

    //The doFilter method is designed 7 to intercept requests. Permission check can be done
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //Get session dialog
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpSession session = httpServletRequest.getSession();
        //If session is equal to null, it means that there is no login
        if (session == null){
            servletRequest.getRequestDispatcher("/login.jsp").forward(servletRequest,servletResponse);
            return;
        }else{
            //Let the program continue to access the resources of the user's target
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }
}

web.xml configuration

<!--  to configure filter filter  -->
    <filter>
        <filter-name>AdminFilter</filter-name>
        <filter-class>AdminFilter.AdminFilter</filter-class>
    </filter>
    
<!--Configure the interception path of the listener-->
    <filter-mapping>
        <!--   Which is the current path for filter use     -->
            <filter-name>AdminFilter</filter-name>
        <!--Configure interception path http://ip:port / Project path / admin / * -- >
            <url-pattern>/admin/*</url-pattern>
    </filter-mapping>

If filter filter and interception are not added, the target resource should be accessed

Note: if you have logged in to the above websites before, you will not intercept through the server after setting the filter listener, but will directly look in the cache. Therefore, the above pages will appear. After clearing the cache, you will intercept and visit login JSP page

3. Complete user login and permission check

web.xml configuration

<!--establish servlet program-->
    <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>loginServlet.LoginServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/loginServlet</url-pattern>
    </servlet-mapping>


<!--  to configure filter filter  -->
    <filter>
        <filter-name>AdminFilter</filter-name>
        <filter-class>AdminFilter.AdminFilter</filter-class>
    </filter>

<!--Configure the interception path of the listener-->
    <filter-mapping>
        <!--   Which is the current path for filter use     -->
            <filter-name>AdminFilter</filter-name>
        <!--Configure interception path http://ip:port / Project path / admin / * -- >
            <url-pattern>/admin/*</url-pattern>
    </filter-mapping>

login Login Class

public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Set the character set to deal with garbled code
        resp.setContentType("text/html;charset=UTF-8 ");
        //Get login information
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //Judge whether the login information is equal to the setting
        if ("gougege".equals(username) && "123456".equals(password)){
            req.getSession().setAttribute("user",username);
            resp.getWriter().write("Login successful");
        }else{
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }
    }
}

filter listener class

public class AdminFilter implements Filter {

    //The doFilter method is designed 7 to intercept requests. Permission check can be done
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //Get session dialog
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpSession session = httpServletRequest.getSession();
        //If session is equal to null, it means that there is no login
        if (session == null){
            servletRequest.getRequestDispatcher("/login.jsp").forward(servletRequest,servletResponse);
            return;
        }else{
            //Let the program continue to access the resources of the user's target
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }
}

login.jsp page

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

visit http://localhost:8080/0808_filter/admin/login.jsp

Enter the correct user name and password to enter

After successful login, a session dialog will be established to store the data in the server. If you access other targets again, you can directly access the target resources.

4.Filter life cycle

The life cycle of Filter contains several methods
(1) Constructor method

public AdminFilter() {
        System.out.println("1.Filter Constructor method AdminFilter()");
    }

(2) init initialization method

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

Note: steps (1) and (2) are executed when the web project is started (Filter has been created)

(3) doFilter filtering method

 //The doFilter method is used to intercept requests. Permission check can be done
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("3.Filter of doFilter()method:Intercept request,Do permission check");

        //Get session dialog
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpSession session = httpServletRequest.getSession();
        //If session is equal to null, it means that there is no login
        if (session == null){
            servletRequest.getRequestDispatcher("/login.jsp").forward(servletRequest,servletResponse);
            return;
        }else{
            //Let the program continue to access the resources of the user's target
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }

Note: in step (3), every time a request is intercepted, it will be executed

(4) Destroy destroy|

 @Override
    public void destroy() {
        System.out.println("4.Filter of destroy()Destruction method");
    }

Note: step (4) will be executed when the web project is stopped (stop the web project and destroy the Filter)

5.FilterConfig class

(1)FilterConfig class is the configuration file class of Filter filter.

(2) Every time Tomcat creates a Filter, it will also create a FilterConfig class, which contains the configuration information of the Filter configuration file.

(3) The function of filterconfig class is to obtain the configuration content of filter filter
① . get the name of Filter and the content of Filter name

 String filterName = filterConfig.getFilterName();
        System.out.println(filterName);

② . get the init- param initialization parameter configured in Filter
xml configuration file

<!--    init-param Multiple groups of parameters can be configured    -->
        <init-param>
            <param-name>username</param-name>
            <param-value>gougege</param-value>
        </init-param>

        <init-param>
            <param-name>password</param-name>
            <param-value>123456</param-value>
        </init-param>

Get by name

		String password = filterConfig.getInitParameter("password");
        System.out.println(password);
        String username = filterConfig.getInitParameter("username");
        System.out.println(username);

③ . get ServletContext object

 ServletContext servletContext = filterConfig.getServletContext();
        System.out.println(servletContext);

6.FilterChain filter chain

(1)FilterChain. The role of the dofilter () method

① If there is another Filter, execute the next Filter
② If there is no next Filter, execute the target resource

(2) Features of multiple Filter execution:
① All filter and target resources are executed in the same thread by default

② When multiple filters are executed together, they all use the same Request object. Intercept the same Request

③ When multiple filter filters are executed, their execution priority is determined by the filter listener on the web The order of matching covers from top to bottom in XML is determined!

For example, the xml configuration is as follows:


Execution sequence

If there is no dofile () method in the filter2 listener

The execution order is

If there is no dofile () method in the filter1 listener

Only the pre code of the filter is executed

7. Interception path of filter

(1) Exact match
For example, it means that the request address must be: http://ip:port/ Project path / login jsp

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

(2) Directory matching
For example, it means that the request address must be: http://ip:port/ Project path / admin / * (all files in admin directory)

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

(3) Suffix matching
For example, it means that the request address must be in The end of html will be intercepted

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

Summary: Filter filter only cares about whether the requested address matches, not whether the requested resource exists!

Keywords: Java servlet filter

Added by silvio on Mon, 27 Dec 2021 00:38:27 +0200