tags:

views:

291

answers:

4

Hi Servlet is also java program but there is no main method in servlet.Who will take role of main method on servet.

+5  A: 

Servlets are designed to run inside a servlet container (eg. Apache Tomcat). Execution of a servlet happens in the following manner: The servlet container calls the GenericServlet.service() method on a servlet which typically calls the appropriate doXxx() method, eg. doGet(), doPost(), etc. The doXxx() method is responsible for interpreting the HTTP request and serving an appropriate response. GenericServlet.service() is roughly analagous to main() in a plain old java class.

Asaph
.. and during startup the servlet container does `HttpServlet servletName = new ServletClass();` based on the `web.xml` or the `@WebServlet` and stores it in memory. Whenever the configured `url-pattern` matches the servlet's one, then the `service()` method will be invoked on the particular instance.
BalusC
+1  A: 

Servlet are deployed on Java application server (servlet container). They are kind of 'passive'. When you write servlet, your servlet code is called by the container whenever there's request or need. So you don't see 'main' in your servlet (the whole thing is not started from servlet), which is inside application server (you could imagine the startup of application server starts from some kind of main).

bryantsai
A: 

If you're looking for an area in a servlet to place code that's run on startup like main() is, take a look at implementing the ServletContextListener interface.

It's two methods are called on application startup and shutdown.

jbruce2112
@jbruce - that is hardly equivalent to main, IMO.
Stephen C
@Stephen - I assumed the question was asked with a need to do some coding like you would in a main() method (such as initializations,connections, etc.), I realize my answer doesn't really reflect this so I elaborated.
jbruce2112
A: 

There is no main method in a Java servlet any more than than an ActionListener on a Swing JButton has a main method. What they both do have are methods that you can hook into when a certain event happens (a click on the JButton for example, or an HTTP PUT request on a HttpServlet). And in both cases, you are provided information about the event that triggered the call - the ActionEvent for the JButton and the ServletRequest for a servlet.

Thinking of servlets in terms of event handlers is probably more useful than trying to think of them like a standalone Java application where you are responsible for the entire control flow.

mattjames