The Web service automatically executes certain types of code at startup.

Source: Internet
Author: User

1. automatically execute code when the server is started or stopped

The principle is to use the servlet listener to create a servlet class and implement the servletcontextlistener interface:

T1.java

Package com. ABC. test;

Import java. Io. file;
Import java. Io. filewriter;
Import java. Io. ioexception;

Import javax. servlet. servletcontextevent;
Import javax. servlet. servletcontextlistener;
Import javax. servlet. http. httpservlet;

Public class T1 extends httpservlet implements servletcontextlistener {
// Execute this event when the server is stopped
Public void contextdestroyed (servletcontextevent SCE ){
Deletefile (); // delete the file created when the server is started
}
// Execute this event when the server starts.
Public void contextinitialized (servletcontextevent SCE ){
Writefile (); // Add a new text file
}

Public void writefile (){
Try {
Filewriter fw = new filewriter ("C:/writedata.txt ");
// Write a string to a file
FW. Write ("Hello world! ");
FW. Write ("Hello everyone! ");
FW. Close ();
} Catch (ioexception e ){
}
}

Public void deletefile (){
File F = new file ("C:/writedata.txt ");
// Check whether the object exists. If yes, delete the object directly.
If (F. exists ()){
F. Delete ();
}
}

}

 

After the class is written, you need to add a listener in Web. XML to enable the servlet class to be automatically executed and add the following content to Web. xml:

<Listener>
<Listener-class> com. ABC. Test. t1 </listener-class>
</Listener>

 

The content in listener-class is the added servlet class.

 

Now I can use it. When I start the Tomcat 5.5 server, I will find that the file writedata.txt is created in the C: root directory, stop the server, and the writedata.txt will be automatically deleted.

 

You may need to read the configuration information when starting the service. You can add the configuration information to Web. XML, such

     <context-param>
<param-name>YourName</param-name>
<param-value>YourValue</param-value>
</context-param>

 

This can be read in servlet:

 this.getServletContext().getInitParameter("YourName");
2. When the Web service starts, it automatically loads the servlet and reads the database content.

Define a servlet in Web. XML as follows:

 

 

<Servlet>
<Servlet-Name> t1 </servlet-Name>
<Servlet-class> com. ABC. Test. t1 </servlet-class>
<Load-on-startup> 1 </load-on-startup>
</Servlet>

<Load-on-startup> indicates whether the Web container loads the servlet at startup.

When the value is 0 or greater than 0, the Web container loads the servlet when the application starts;

When it is a negative number or when it 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.

 

In writing this servlet, You need to rewrite the init () method. Others such as doget () and dopost () cannot be executed. The following is a simple example:

Package com. ABC. test;

Import javax. servlet. servletexception;
Import javax. servlet. http. httpservlet;

Public class T1 extends httpservlet {

Public T1 (){
Super ();
}

Public void Init () throws servletexception {
System. Out. println ("test ");
}
}

Restart the Web Container and you can see the line "test" in the console.

Then let's modify our code so that the servlet can read the database content and perform relevant processing.

I use the hibernatetemplate and jdbctemplate of spring to operate the database. The database is accessed using bean injection. The service is injected into the action to read database data, in fact, the key now is to get the instantiation object of this service. The previous article I wrote can be used here: JSP Study Notes (50 ): automatically load configuration files in spring and read Methods

 

Now let's take a look at how to write this servlet. The Code is as follows:

Package com. ABC. test;

Import javax. servlet. servletcontext;
Import javax. servlet. servletexception;
Import javax. servlet. http. httpservlet;

Import org. springframework. Web. Context. webapplicationcontext;
Import org. springframework. Web. Context. Support. webapplicationcontextutils;

Import com. ABC. Test. service1;

Public class T1 extends httpservlet {

Public T1 (){
Super ();
}

Public void Init () throws servletexception {
Servletcontext SC = getservletcontext ();
Webapplicationcontext AC = webapplicationcontextutils. getrequiredwebapplicationcontext (SC );


Service1 service = (service1) AC. getbean ("yourserviceid ");
List list = service. getlist ();
// List is the content obtained from the database. You can perform related processing.
}
}

 

Yourserviceid is the <bean id = "yourserviceid"> configured in the spring configuration file. It's easy. Then you can perform related operations, such as executing an SQL script, or putting the data obtained from the database into the application or static string.

 

3. automatically load configuration files in spring and read Methods

 

Configure web. xml and add the following content:

      <context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>

 

In this way, when the Web Container starts, the spring configuration file will be automatically loaded. When there are multiple configuration files, they can be separated by spaces, commas, or colons.

 

Next we can use it directly, instead of re-loading through classpathxmlapplicationcontext. The following is the obtained code:

          ServletContext sc = ServletActionContext.getServletContext(); 
// Obtain the servletcontext. In different scenarios, the acquisition method is different. Here is the acquisition method in the action class in struts2.
Webapplicationcontext AC = webapplicationcontextutils. getrequiredwebapplicationcontext (SC );
AC. getbean ("beanid"); // obtain the bean ID in the configuration file.

<Servlet>
<Servlet-Name> t1 </servlet-Name>
<Servlet-class> com. ABC. Test. t1 </servlet-class>
</Servlet>

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.