Punith Raj
Punith Raj

Reputation: 2195

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

Upvotes: 8

Views: 3501

Answers (2)

MaDa
MaDa

Reputation: 10762

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.

Upvotes: 2

Piotr Nowicki
Piotr Nowicki

Reputation: 18224

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.

Upvotes: 8

Related Questions