Java Web deployment startup thread (Listening to socket, etc)

Source: Internet
Author: User

 

 

 

Very simple ......

Write another Servlet and start the corresponding thread in the init function.

Add this servlet to Web. XML, for example

<Servlet>
<Servlet-Name> echoservicestartupservlet </servlet-Name>
<Servlet-class> echoservice. echoservicestartupservlet </servlet-class>
<Load-on-startup> 3 </load-on-startup>
</Servlet>

Pay attention to load-on-startup.

The value after the number must be greater than 0, indicating the priority. The smaller the value, the higher the priority.

If this parameter is not set or smaller than 0, the instance is not started.
But there is a big problem !! That is, when Tomcat is disabled, the thread may not be released.

Listener should be used.

Code

  Public     Class  Serversocketlistener  Implements  Servletcontextlistener {
Private Echoserverthread;

Public Void Contextinitialized (servletcontextevent event ){
String Port
= Event. getservletcontext (). getinitparameter ( " Socketport " );
// Event. getservletcontext (). log ("++ ");
// Event. getservletcontext (). Log ("++ socket service started with the Web ");
Echoserverthread = New Echoserverthread (integer. parseint (port ));
Echoserverthread. Start ();
// Event. getservletcontext (). Log ("++ socket service has been started, Port:" + port + "++ ");
}

// When Tomcat is closed, the thread is closed and the port is released.
Public Void Contextdestroyed (servletcontextevent event ){
Echoserverthread. stopthread ();
}
}

The START and release operations are now available ~~~

 

Configure the following in Web. xml:

Add the following content to the Web-app node:

<Context-param>
<Param-Name> socketport </param-Name>
<Param-value> 2230 </param-value>
</Context-param>
<Listener>
<Description> the socket service is started with the Web startup. </description>
<Listener-class> echoservice. serversocketlistener </listener-class>
</Listener>

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.