8

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

Punith Raj
  • 2,164
  • 3
  • 27
  • 45

2 Answers2

8

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.

Piotr Nowicki
  • 17,914
  • 8
  • 63
  • 82
  • Actually one of the security tool is throwing error, saying... A Servlet defined in web.xml cannot be accessed without a corresponding servlet mapping. – Punith Raj Sep 26 '12 at 13:30
  • 1
    Well, its true :-) However, I don't think it should show an error - a warning would be more appropriate in my opinion. – Piotr Nowicki Sep 26 '12 at 13:34
2

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.

Arjan Tijms
  • 37,782
  • 12
  • 108
  • 140
MaDa
  • 10,511
  • 9
  • 46
  • 84