Monday, March 2, 2015

Embedding Tomcat inside Java Program

Apache Tomcat is one of the most popular open source application servers that is been use today. What we usually do is run Tomcat server and deploy our webapps inside the Tomcat.
But we also can embed Tomcat inside our java application and do all stuffs through our own program. This is just a simple example showing how to embed the tomcat, start the server and put a servlet inside that.

I'm using Intellij Idea IDE. But you can use any IDE that you like. First create a new maven project and give an artifact id, group id and version that you like.
We need to add following tomcat dependencies to the pom file.

Finally pom file looks like
Now create a Java file with following content

Now run this class. When your program starts to run you will see some log entries getting on your console. If the sever get started successfully go to your web browser and type http://localhost:8888/
You will see something like following image on browser.