Filter and Listener related learning notes

Keywords: JSP xml Mobile encoding

Filter: filter

  • concept
    • When accessing the resources of the server, the filter can intercept the request and complete some special functions.
    • Generally used to complete general operations. (such as login authentication, unified encoding, sensitive character filtering...)
  • step
    1. Define a class to implement interface Filter
    2. Replication method
    3. Configure interception path
      1. web.xml
      2. annotation
@WebFilter("/*")	//This filter is executed before all resources are accessed
public class FilterDemo implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //Yes request Object request message enhancement
        System.out.println("FilterDemo Was executed....");
        
        filterChain.doFilter(servletRequest,servletResponse);//Release
        
        //Yes response Object response message enhancement
        System.out.println("FilterDemo Come back....");
    }

    @Override
    public void destroy() {}
}

Filter details

web.xml to configure

<filter>
	<filter-name>demo1</filter-name>
	<filter-class>cn.comany.web.filter.FilterDemo</filter-class>
</filter>
<filter-mapping>
	<filter-name>demo</filter-name>
	<!-- Intercept path -->
	<url-pattern>/*</url-pattern>
</filter-mapping>

Filter execution process

  1. Execution filter
  2. (release) resources after release
  3. Back to execute the code below the filter release code

Filter life cycle approach

  1. Init: after the server starts, it creates the Filter object and then calls the init method. (execute only once for loading resources)
  2. doFilter: every time a request is intercepted, it will be executed. (executed multiple times)
  3. Destroy: after the server is shut down, the Filter object is destroyed. If the server is shut down normally, the destroy method is executed. (execute only once to release resources)

Filter configuration details

Intercept path configuration
  • Specific resource path:/ index.jsp Access only index.jsp The filter is only executed when the resource
  • When intercepting directory / user / * to access resources under / user, the filter will be executed
  • Suffix interception: *. jsp when accessing the resource with suffix jsp, the filter will be executed
  • Block all resources: / * access to any resources, the filter will be executed
Interception mode configuration: the access mode of resources
Annotation configuration
  • Set the dispatcherTypes property
    • REQUEST: the default value. Browser requests resources directly
    • FORWARD: FORWARD access resources
    • INCLUDE: contains access resources
    • ERROR: ERROR jump resource
    • ASYNC: asynchronous access to resources
//Browser direct request index.jsp Resources will be executed
@WebFilter(value="/index.jsp",dispatcherTypes=DispatcherType.REQUEST)
//Only forward access index.jsp The filter will be executed
@WebFilter(value="/index.jsp",dispatcherTypes=DispatcherType.FORWARD)
//Browser direct request index.jsp  Or forward access index.jsp The filter will be executed
@WebFilter(value="/index.jsp",dispatcherTypes={DispatcherType.REQUEST,DispatcherType.FORWARD})
public class FilterDemo implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("FilterDemo Was executed....");
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {}
}
web.xml to configure
  • Just set the < dispatcher > < dispatcher > label

Filter chain (configure multiple filters)

  • Execution sequence: if there are two filters (filter 1 and filter 2)
    1. Filter 1
    2. Filter 2
    3. Resource execution
    4. Filter 2
    5. Filter 1
  • Filter sequencing problem:
    • Annotation configuration: compare according to the string comparison rule of class name, and execute first if the value is small
      • For example: after and BFilter, after is executed first.
    • web.xml Configuration: < filter mapping > who defines the top and who executes first

Enhance the function of objects

  • Design patterns: some common ways to solve fixed problems

Decoration mode

proxy pattern

  • concept
    • Real objects: represented objects
    • Proxy objects: proxy real objects
    • Proxy mode: proxy object proxy real object to enhance the function of real object
Implementation mode
  • Static proxy: there is a class file describing the proxy pattern
  • Dynamic proxy: forming proxy class in memory
    • Implementation steps:
      1. Proxy objects and real objects implement the same interface
      2. Proxy object= Proxy.newProxyInstance();
      3. Using proxy objects to call methods
      4. Enhancement method
    • Enhancement method
      • Enhanced parameter list
      • Enhanced return value type
      • Enhance method body execution logic
//Real class
public class Phone implements SalePhone {
    @Override
    public String sale(double money){
        System.out.println("flower"+money+"Bought a mobile phone");
        return "XX mobile phone";
    }
    @Override
    public void show(){
        System.out.println("Very happy");
    }
}

public class ProxyTest {
    public static void main(String[] args) {
        //1. Create real objects
        Phone phone = new Phone();
        //2. Dynamic proxy enhanced Phone object
        /*
         * Three parameters:
         * 1.Class loader: real object. getClass().getClassLoader()
         * 2.Interface array: real object. getClass().getInterfaces()
         * 3.Processor: new InvocationHandler()
         * */
        SalePhone proxyPhone = (SalePhone) Proxy.newProxyInstance(phone.getClass().getClassLoader(), phone.getClass().getInterfaces(), new InvocationHandler() {
            /*
             * Methods written by the agent logic: all methods called by the agent object trigger the method execution
             * Parameters:
             *   1.proxy: Proxy object
             *   2.method: Method called by proxy object, encapsulated as object of
             *   3.args: The actual parameters passed when the proxy object calls a method
             * */
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                /*
                System.out.println(method.getName());	//proxyPhone.show();The proxy object calls the method to output show
                System.out.println(args[0]);	//proxyPhone.sale(8000);The proxy object calls this method to output 8888
                */
                //Judge whether it is sale method
                if (method.getName().equals("sale")) {
                    //1. Enhanced parameters
                    double money = (double) args[0];
                    money *= 0.85;
                    //Call this method with a real object
                    String obj = (String) method.invoke(phone, money);
                    //2. Enhanced return value
                    return obj + "_headset";
                } else {
                    Object obj = method.invoke(phone, args);
                    return obj;
                }
            }
        });
        //2. Call method
        String newPhone = proxyPhone.sale(8888);
        System.out.println(newPhone);
        proxyPhone.show();	//Object calling the agent
    }
}

Listener: listener

  • Concept: one of the three major components of the web.
    • Event monitoring mechanism
      • Event: one thing
      • Event source: where the event occurred
      • Listener: an object
      • Register listening: binding events, event sources and listeners together. When an event occurs on the event source, the listener code is executed.

ServletContextListener

  • Listen to the creation and destruction of ServletContext object

  • method

    • void contextDestroyed(ServletContextEvent sce): this method will be called before the ServletContext object is destroyed
    • void contextInitialized(ServletContextEvent sce): this method will be called after the ServletContext object is created
  • step

    1. Define a class to implement the ServletContextListener interface

    2. Replication method

    3. to configure

      1.web.xml

      <listener>
      	<listener-class>cn.company.web.listener.ContextLoaderListener</listener-class>
      </listener>
      <!-- Specify initialization parameters -->
      <context-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>/WEB-INF/classes/applicationContext.xml</param-value>
      </context-param>
      

      2. Note: @ WebListener

@WebListener
public class ContextLoaderListener implements ServletContextListener {
    /*
    * Listen for the creation of the ServletContext object. Automatically create the ServletContext object after the server starts
    * Called automatically after the server starts
    * */
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        //Load resource file
        //1. Get the ServletContext object
        ServletContext servletContext = servletContextEvent.getServletContext();
        //2. Load resource file
        String contextConfigLocation = servletContext.getInitParameter("contextConfigLocation");
        //3. Get the real path
        String realPath = servletContext.getRealPath(contextConfigLocation);
        //4. Load into memory
        try {
            FileInputStream fis = new FileInputStream(realPath);
            System.out.println(fis);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("ServletContext Object is created...");
    }

    /*
    * After the server is shut down, the ServletContext object is destroyed. This method is called when the server is shut down normally
    * */
    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {System.out.println("ServletContext The object was destroyed...");}
}

Posted by RClapham on Fri, 12 Jun 2020 22:09:52 -0700