Why don't I see any main method in this java dynamic web project?

橙三吉。 提交于 2019-11-29 01:27:16

Web applications don't have a main; the 'program' that is running is actually the web container (Apache Tomcat, Glassfish, JBoss, Weblogic, whatever) and that program will service the web application(s) you deploy into it. You might want to read the JEE tutorial to learn and understand what a Java web environment is.

https://docs.oracle.com/javaee/7/tutorial/

There is still a main method, it's just not written by the developer of the application but by the developer of the container.

You can still see the main method being called by using the debugger like this:

  • Put a breakpoint in some initialization method, such as the init method of some servlet Servlet.init()
  • When the breapoint hits, scroll down the call trace and the main method should be at the bottom.

This is an example with jetty:

To see this we need to put the breakpoint in an initialization method so that we get the main thread of the application.

Putting the breakpoint in the processing of a request instead of an initialization method would show Thread.run() at the bottom of the stack trace and not main().

Thread.run() is the equivalent of the main method for threads other than the main thread.

So the main method still exists, it's just being handled at the level of the container.

You don't see any explicit main method just because it is a Web project. This project is built into a web application archive (WAR) file which is deployed into a web server / servlet container, e.g. Tomcat in this tutorial.

Web applications does not have to contain main methods. This is because you don't need to explicitly start any Java process from within your webapp. Somewhere in its depths, Tomcat calls a main method of the code it has been built from. This happens at server startup time.

Then, it will bind your code to incoming HTTP calls, but it will not start new processes for that. It will rather start new threads.

Web applications are not standalone application, they run on some applications what we call servletContainer in java context so there is no main method or java process(os) for any web application. They are just deployed on those containers that have main method and java process in OS runtime.

Hitanshi Mehta

If you've created a basic program in Java then you must know that every Java program has a main() method, which is the starting point of the program. So, how come servlets don't have a main()? That is because servlets are served using via Web containers. Web container will perform all underlying work on behalf of servlet so programmer can focus on business logic. When a client requests a servlet, server hands requests to a Web container where the servlet is deployed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!