Servlet notes-JavaWeb three major components Servlet, Filter, Listener

Three major components of JavaWeb

Servlet (mentioned before)

Filter

concept

When accessing server resources, the filter can intercept the request and perform some special functions. For example, you can use filters to uniformly set codes for requests, perform login verification, and filter sensitive words. Filters are generally used to complete some common functions

Quick start

Steps to write Filter

  1. Define a class to implement the Filter interface

  2. Rewrite interface method

  3. Configure Filter (mainly configure the interception path, such as /*intercepting all requests)

    1. web.xml configuration
    2. Annotation configuration @WebFilter
  4. Code

    public class LogFilter implements Filter {
          
          
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
          
          
            System.out.println("init...");
        }
    
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
          
          
            HttpServletRequest request = (HttpServletRequest) servletRequest; 
            System.out.println("Calling -> " + request.getRequestURL());
            //放行
            filterChain.doFilter(servletRequest,servletResponse);
            System.out.println("Finished -> " + request.getRequestURL());
        }
    
        @Override
        public void destroy() {
          
          
            System.out.println("destroy...");
        }
    }
    
Filter details
  1. Filter execution process (similar to AOP)

  2. Filter life cycle

    1. init(): After the server is started, create a Filter object, call init, and execute it only once
    2. doFilter(): Each time a request is intercepted, doFilter is executed, which will be executed multiple times
    3. destroy(): The server is shut down normally, call destroy, destroy the Filter object, and execute it only once
  3. Detailed configuration

    1. Intercept path configuration

      1. /index.jsp Block specific resources
      2. /login/* Intercept a certain type of resource
      3. *.jsp Intercept a certain class
      4. /* Block all
      	<filter>
              <filter-name>logFilter</filter-name>
              <filter-class>com.yogurt.filter.LogFilter</filter-class>
          </filter>
          
          <filter-mapping>
              <filter-name>logFilter</filter-name>
              <url-pattern>/*</url-pattern>
          </filter-mapping>
      
    2. Interception mode configuration

      1. The method refers to the way the resource is accessed, such as the browser directly requesting access, or the server forwarding access. If this parameter is specified, Filter will only perform interception when the url-pattern is satisfied and the request mode meets the specified value of this parameter.

      2. Just set the dispatcherType attribute

        1. REQUEST browser directly requests access (default value)
        2. When the FORWARD server forwards access
        3. INCLUDE contains access
        4. ERROR error jump resource
        5. ASYNC asynchronous access to resources
      3. web.xml configuration

        	<filter-mapping>
                <filter-name>logFilter</filter-name>
                <url-pattern>/*</url-pattern>
                <dispatcher>REQUEST</dispatcher>
            </filter-mapping>
        
      4. Annotation configuration

        @WebFilter(urlPatterns = "/*",dispatcherTypes = DispatcherType.FORWARD)
        
        package javax.servlet;
        public enum DispatcherType {
                  
                  
            FORWARD,
            INCLUDE,
            REQUEST,
            ASYNC,
            ERROR;
            private DispatcherType() {
                  
                  
            }
        }
        
  4. Filter chain

    Multiple filters can be configured, and each filter is executed in chain. The test found that Filter initialization is initialized according to the dictionary name of the Filter, whether it is web.xml configuration or annotation configuration, web.xml configuration, regardless <filter>of the location of the label.

    1. Execution order

      1. Annotation configuration:

        The default is to execute each filter in sequence according to the string order of the filter name

        If there are 2 Filters, AFilter and BFilter, AFilter will be executed first, and BFilter will be executed later

      2. web.xml configuration:

        <filter-mapping>The label is executed in the front Filter first, and the configuration is executed later

        Example

        	<!-- 则会先执行cidFilter -->
        	<filter-mapping>
                <filter-name>cidFilter</filter-name>
                <url-pattern>/*</url-pattern>
            </filter-mapping>
        
            <filter-mapping>
                <filter-name>logFilter</filter-name>
                <url-pattern>/*</url-pattern>
            </filter-mapping>
        
Filter case
  1. Login authentication (the most basic content of the permission control framework)

    The filter verifies whether the session contains user information. If it does, it means that the user has logged in and let it go; otherwise, it prompts that the user is not logged in and jumps to the login page.

    Note: When configuring the interception path of Filter, you may need to pay attention to the release of static resources.

    Ideas:

    • Determine whether it is a login-related resource

      • Yes. It is released directly. (For example, when requesting a login page, it is a login operation, so it is not intercepted)

        (Note that static resources, such as css/js/captchas and other resources also need to be released. Otherwise, the page will be abnormal)

      • No, intercept and determine whether the user is logged in

    • Determine whether the user is logged in (judged by the data in the session)

      • Yes. Then release
      • No, if you are not logged in, you will jump to the login page and prompt the user to log in. After the user logs in, the information of the logged in user will be stored in the session
  2. Sensitive word filtering

    1. Sensitive word data table
    2. If there are sensitive words in the requested input parameters, replace with ***
    3. Because the request has only one getParameter to obtain request parameters, but there is no such method as setParameter to modify the parameters in the request, it is necessary to enhance the getParameter method of the request object (AOP), generate a new request object, and pass it on.

    Need to enhance the request object, you can use JDK dynamic proxy

Listener

  1. Concept: Event Listener

  2. Event monitoring mechanism

    1. Event: a thing, such as a click event
    2. Event source: where the event occurred
    3. Listener: an object
    4. Register the listener: bind the event, event source, and listener together. When an event occurs on the event source, the listener code is executed
  3. ServletContextListener

    1. Inclusion method

      void contextInitialized(ServletContextEvent sce)

      After the ServletContext object is created, call this method

      void contextDestroyed(ServletContextEvent sce)

      Before the ServletContext object is destroyed, call this method

    2. Steps to implement a Listener to monitor Servlet

      1. Define a class that implements the ServletContextListener interface

        @WebListener
        public class YogurtListener implements ServletContextListener {
                  
                  
        	@Override
        	public void contextInitialized(ServletContextEvent sce) {
                  
                  
        		//可以加载一些初始资源
        		ServletContext servletContext = sce.getServletContext();
        		String location = servletContext.getInitParameter("location");
        		System.out.println(location);
        		System.out.println("启动拉");
        	}
        
        	@Override
        	public void contextDestroyed(ServletContextEvent servletContextEvent) {
                  
                  
        
        	}
        }
        
      2. Configuration

        1. web.xml configuration

          <<listener>
                  <listener-class>com.yogurt.listener.YogurtListener</listener-class>
              </listener>
          

          You can configure the contextParam in web.xml, and then monitor the Servlet startup to obtain these parameters to load some resources when the Servlet starts (previously when handwriting Spring, this method was used to initialize the Spring container)

          <context-param>
                  <param-name>location</param-name>
                  <param-value>classpath:yogurt.properties</param-value>
              </context-param>
          
        2. Annotation configuration

          On the Listener class annotated directly @WebListenerto

Guess you like

Origin blog.csdn.net/vcj1009784814/article/details/106107400