Tomcat loads a servlet at startup, and tomcat loads the servlet
When we build a java project, several functions need to load servlet or implement a common method. Although we can load each function in sequence, however, when a servlet or method is frequently loaded and applied, we can leave the idea of Object-oriented Thinking empty, but we can't really say it.
Therefore, for such Servlets, We need to load them directly at Tomcat startup, such as initializing information and reading configuration files.Configuration FileTo achieve this:
First, The AbstractItemServlet class encapsulates the corresponding Init method:
<Span style = "font-family: FangSong_GB2312; font-size: 18px;"> package com. bjpowernode. drp. util. servlet; import javax. servlet. servletException; import javax. servlet. http. httpServlet; import com. bjpowernode. drp. util. beanFactory;/***** responsible for System initialization at server startup * @ author chao **/public class InitServlet extends HttpServlet {@ Overridepublic void init () throws ServletException {System. out. println ("create BeanFactory ..... "); // Place the abstract factory in servletContext BeanFactory beanFactory = BeanFactory. getInstance (); this. getServletContext (). setAttribute ("beanFactory", beanFactory) ;}</span>
Second, Configure the abstract servlet in the project configuration file web. xml (Path:/WebRoot/WEB-INF/web. xml:
<Span style = "font-family: FangSong_GB2312; font-size: 18px;"> <! -- Set InniServlet as soon as tomcat is started --> <servlet-name> InitServlet </servlet-name> <servlet-class> com. bjpowernode. drp. util. servlet. initServlet </servlet-class> <load-on-startup> 2 </load-on-startup> </servlet> </span>
In this way, the init () method of com. bjpowernode. drp. util. servlet. InitServlet can be called at Tomcat startup.
Where, <Load-on-startup> N </load-on-startup> indicates whether the servlet is loaded when the container is started. When the value is 0 or greater than 0, it indicates that the servlet is loaded when the application is started. When it is a negative number or is not specified, it indicates that the container is loaded only when the servlet is selected. The smaller the positive value, the higher the priority of starting the servlet.
With this method, we can not only save the execution time and space for each call to this method, but also perfectly implement the object-oriented thinking. Why are we happy?
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.