Loading order of context-param, listener, filter, servlet in JavaWeb web.xml (emphasis)

in conclusion

Let me talk about the conclusion first, the loading order in JavaWeb's web.xml is:

context-param -> listener -> filter -> servlet

analysis

The following describes the web program running in tomcat as an example. First, the web program will read the web.xml file.

1、context-param

<context-param></context-param>This tag is the context parameter of the web program and the initialization parameter of the startup. The first thing the web program parses is this tag, and the tag is parsed first no matter where the tag is. After parsing the context-param tag above, a ServletContext object will be created, and the entire Application of the web project will share this ServletContext. Speaking of this, there is a problem to pay attention to, that is, the " Log4j problem when Tomcat deploys multiple projects ".

2、listener

<listener></listener>This label is a listener. After the above steps are completed, Tomcat will create an instance of the listener that is the object in the label. There will be an contextInitialized(ServletContextEvent args)initialization method in the monitor , in this method you can get the ServletContext object to get the value of context-param

ServletContext = ServletContextEvent.getServletContext()       
context-param = ServletContext.getInitParameter("context-param的key")   

3、filter

<filter></filter>This is a filter, which is instantiated after completing the above steps. Note: If there are multiple filters, execute them in the order of the filters in web.xml.

4、servlet

<servlet></servlet>This belongs to the service interface, and this is instantiated after all of the above are completed.
In the servlet configuration, <load-on-startup>the meaning is:

  1. Zero or positive number means that the servlet is started when the service is started;
  2. The smaller the positive value, the higher the priority of starting the servlet;
  3. Negative value or no such configuration will be executed when used.

to sum up

If it is in the Springmvc or Struct interceptor拦截器framework, the execution sequence is as follows:

context-param -> listener -> filter -> interceptor -> 控制器

Reference:
"The execution order and difference between Interceptor and Filter"

Guess you like

Origin blog.csdn.net/u011047968/article/details/108094213