Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we invoke a servlet without <servlet-mapping> in web.xml entry

In one of the code i saw that, there was no <servlet-mapping> tags and only its declared as below

<servlet>
    <servlet-name>startServlet</servlet-name>
    <servlet-class>com.login.StartupServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

can this work without <servlet-mapping> and work on <load-on-startup>1</load-on-startup>??

This servlet will get loaded on server startup to connect to DB and do few operation on caching.

PS: this is on Servlet 2.0+ version and not annotated.

thanks Punith

like image 724
Punith Raj Avatar asked Sep 26 '12 13:09

Punith Raj


2 Answers

The code you posted defines something you might call an "initializer Servlet". It is not directly accessed from the outside world (using an URL) but it will be started by the Servlet container.

It is valid but it can't be accessed by the clients. It's often used for initialization purposes. You can access servlets without <servlet-mapping> using Servlets 3.0 annotations.

Mind that <load-on-startup> doesn't hold true/false value (0/1) but it defines an integer which is an order of startup. Higher number means that the Servlet will be loaded after the ones with lower number.

like image 167
Piotr Nowicki Avatar answered Oct 21 '22 14:10

Piotr Nowicki


This pattern is often used for initialization of a Java EE web application. For example, it's a popular workaround for yearned @Singleton annotation introduced in EJB 3.1.

like image 21
MaDa Avatar answered Oct 21 '22 15:10

MaDa