Initialization Loading Order of web.xml in Java Web

Posted by designergav on Tue, 02 Jul 2019 00:08:54 +0200

Requirement description

When doing a project, in order to save time, initially put the initialization configuration in each class static loading, initialization configuration more than one, want to tidy it up, here use init method initialization in servlet.

Description of web.xml

First, understand the loading order of elements in web.xml:

  • After launching the web project, the web container first goes back to the web.xml file and reads it.

  • The container creates a ServletContext (servlet context), which is shared by all parts of the entire web project.

  • The container will be converted to key-value pairs and handed over to servletContext

  • Class instances in container creation to create listeners

  • The container loads the filter and creates the filter. Note that the corresponding filter-mapping must be placed behind the filter.

  • Container loads servlet s in Load-on-startup order

Complete loading order: ServletContext - > context-param - > listener - > filter - > Servlet

Configuration implementation

InitServlet.java:

/**
 * Initialize system parameters
 * Founder Kebang Network
 * Established May 10, 2017
 *
 */
public class InitServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    @Override
    public void init(){
        try {
            if(Constants.PAY_URL.size()==0){
                List<CommonEntity> listPayUrl = PropertiesListUtil.listPayUrl();
                for(CommonEntity entity:listPayUrl){
                    Constants.PAY_URL.put(entity.getEntityCode(), entity.getEntityName());
                }
            }
            LogUtil.info("Buddha's Blessing       Never shut down     Never BUG : Initialize the number of system data:"+Constants.PAY_URL.size());

            Configs.init("zfbinfo.properties");
            LogUtil.info("Initializing Alipay configuration information");

            SDKConfig.getConfig().loadPropertiesFromSrc();
            LogUtil.info("Initialize UnionPayment Configuration Information");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * Reload configuration file
     * @Author  Kebang Network
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException 
     * @Date    2017 May 10, 2001
     * Update logs
     * 2017 Zhang Zhipeng was founded for the first time on May 10, 2001
     *
     */
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Constants.PAY_URL = new ConcurrentHashMap<String, String>();
        List<CommonEntity> listPayUrl = PropertiesListUtil.listPayUrl();
        for(CommonEntity entity:listPayUrl){
            Constants.PAY_URL.put(entity.getEntityCode(), entity.getEntityName());
        }
        LogUtil.info("Initialize the number of system data:"+Constants.PAY_URL.size());
    }
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}

web.xml: (partial configuration)

<!-- Initial basic data-->
    <servlet>
        <servlet-name>InitServlet</servlet-name>
        <servlet-class>com.acts.web.common.servlet.InitServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>InitServlet</servlet-name>
        <url-pattern>/InitServlet</url-pattern>
    </servlet-mapping>

Introduction to servlet

What is servlet

Serlet is a technology provided by sun Company for developing dynamic web. Users need to complete the following two steps if they want to send a dynamic web resource (that is, to develop a Java program to output data to the browser):

  1. Write a Java class to implement the servlet interface.
  2. Deploy the developed Java classes to the web server.

According to a convention of address, we usually call the java program which implements the servlet interface as Servlet.

Running process of servlet

  1. The browser makes a request and is fetched by the web container
  2. The Web server first checks whether the instance object of the Servlet has been loaded and created. If so, step 4 will be implemented directly, otherwise step 2 will be implemented.

  3. Load and create an instance object of the Servlet and call the init() method of the Servlet instance object.

  4. Create an HttpServletRequest object for encapsulating HTTP request messages and an HttpServletResponse object representing HTTP response messages, then call the service() method of the Servlet and pass in the request and response objects as parameters.

  5. Before the WEB application is stopped or restarted, the Servlet engine will uninstall the Servlet and call the destroy() method of the Servlet before uninstalling it.

servlet initialization

  • When load-on-startup >= 0, it means loading immediately after the start of web application. The smaller the value of load-on-startup, the higher the priority of loading. If the load-on-startup value of two servlets is the same, the loading priority of the two servlets is determined by the container.

  • When load-on-startup is not configured, the loading of the servlet is determined by the container.

After configuring load-on-startup, the servlet loads immediately after startup, but only invokes the init() method of the servlet to initialize the resources associated with the servlet. After successful initialization, the servlet can respond to web requests; if load-on-startup is not configured, the container will first detect whether the servlet is initialized when it first responds to web requests. If it is not initialized, init() of the servlet will be invoked to initialize first and then respond to requests after successful initialization.

PS: In general, when we develop web applications, we configure this parameter, which has two advantages:
1. If the initialization process fails, the container will prompt the start-up failure, at which time we can know the relevant errors in advance;
2. Configuring this parameter is equivalent to transferring the work of initializing servlet s to the container startup process, so that the container can respond to web requests as soon as the startup is successful.

Some official web notes on load-on-startup:

If the value is a negative integer, or the element is not present, the container is free to load the servlet   
whenever it chooses. If the value is a positive  
integer or 0, the container must load and  initialize the servlet as the application is  deployed.   

Be careful

When using servlets, they usually inherit HTTP servlets and implement doGet or doPost methods respectively. But in this case, it should be noted that the servlet is not thread-safe. It is executed by a single instance with multiple threads. When accessing the same resource concurrently (member variables, etc.), thread security problems may arise.

Small railway station: http://blog.52itstyle.com/

Topics: Java xml network Web Server