What acts as the "main method" in the servlet?

A servlet is also a Java program, but there is no main method in a servlet. Who will take on the role of the main method in servet.

+7
java servlets
source share
5 answers

Servlets are designed to work inside a servlet container (e.g. Apache Tomcat). Servlet execution is as follows: the servlet container calls the GenericServlet.service() method on the servlet, which usually calls the corresponding doXxx() method, for example. doGet() , doPost() , etc. doXxx() is responsible for interpreting the HTTP request and executing the corresponding response. GenericServlet.service() roughly the same as main() in the regular old java class.

+13
source share

Servlet runs inside the container (ex: tomcat). This container does its job under jvm. Here, the container accepts "no main method". In a simlple java program, the main method reports the initial control flow of execution. But in the case of using the servlet database web application, the jvm dose does not require a search for the main method. The servlet container tells jvm to start the control flow.

+2
source share

A servlet is deployed to a Java application server (servlet container). They are "passive." When you write a servlet, your servlet code is called by the container whenever a request or need is made. Thus, you do not see the β€œmain” in your servlet (all this does not start from the servlet) that is inside the application server (you can imagine that the application server starts from some kind of main one).

+1
source share

If you are looking for an area in the servlet to host the code that starts at startup (similar to main ()), take a look at the ServletContextListener implementation.

Its two methods are invoked when starting and ending applications.

+1
source share

There is no main method in the Java servlet no more than the ActionListener in Swing JButton has the main method. They both have methods that you can connect to when a specific event occurs (for example, clicking on a JButton or an HTTP PUT request on an HttpServlet). And in both cases, you are provided with information about the event that caused the call - ActionEvent for JButton and ServletRequest for servlet.

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

0
source share

All Articles