Anton Arhipov is a Software Developer and Product Lead for JRebel, the productivity tool for Java developers. Anton’s professional interests include Java and related, programming languages and middleware. You can follow Anton on Twitter (@antonarhipov) and find him on LinkedIn (linkd.in/aarhipov). Anton has posted 18 posts at DZone. You can read more from them at their website. View Full User Profile

Embedded Tomcat, The Minimal Version

07.08.2011
| 30559 views |
  • submit to reddit

Tomcat 7 has been improved a lot and along with everything else that it brings, a very nice feature is provided - an API for embedding Tomcat into your application. The API was provided in earlier versions of Tomcat but it was quite cumbersome to use.

To to start the embedded version of Tomcat one may need to build the required JARs.

 svn co https://svn.apache.org/repos/asf/tomcat/trunk tomcat
 cd tomcat
 ant embed-jars
 ls -l output/embed
total 5092
-rw-r--r-- 1 anton None 56802 2011-03-06 17:09 LICENSE
-rw-r--r-- 1 anton None 1194 2011-03-06 17:09 NOTICE
-rw-r--r-- 1 anton None 1690519 2011-03-06 17:09 ecj-3.6.jar
-rw-r--r-- 1 anton None 234625 2011-03-06 17:09 tomcat-dbcp.jar
-rw-r--r-- 1 anton None 2402517 2011-03-06 17:09 tomcat-embed-core.jar
-rw-r--r-- 1 anton None 781989 2011-03-06 17:09 tomcat-embed-jasper.jar
-rw-r--r-- 1 anton None 34106 2011-03-06 17:09 tomcat-embed-logging-juli.jar

The following snippet demonstrates the embedded Tomcat usage with a deployed servlet instance.

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.Writer;

public class Main {

  public static void main(String[] args)
  throws LifecycleException, InterruptedException, ServletException {
    Tomcat tomcat = new Tomcat();
    tomcat.setPort(8080);

    Context ctx = tomcat.addContext("/", new File(".").getAbsolutePath());

    Tomcat.addServlet(ctx, "hello", new HttpServlet() {
      protected void service(HttpServletRequest req, HttpServletResponse resp) 
      throws ServletException, IOException {
        Writer w = resp.getWriter();
        w.write("Hello, World!");
        w.flush();
      }
    });
    ctx.addServletMapping("/*", "hello");

    tomcat.start();
    tomcat.getServer().await();
  }

}

The only two JARs required are tomcat-embed-core.jar and tomcat-embed-logging-juli.jar. It means that there will be no JSP support and pooling will also be disabled. But that's enough to start a servlet and in most cases that is what you probably need. 

From http://arhipov.blogspot.com/2011/03/embedded-tomcat-minimal-version.html

Published at DZone with permission of its author, Anton Arhipov.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags:

Comments

othman El moulat replied on Mon, 2011/07/11 - 8:35am

how do you invoke servlet url ? after i run this application i go to browser and type : http//localhost:8080 . but i get an error : resource not found!

any Idea what's wrong?

Anton Arhipov replied on Mon, 2011/07/11 - 10:04am

@othman

It should be defined by the mapping:

ctx.addServletMapping("/*", "hello");

You may want to take a look at one other example of the same thing:

https://github.com/antonarhipov/nanorest/blob/master/src/main/java/org/arhan/nanorest/Main.java

It uses org.apache.catalina.Wrapper to register the servlet, but it is even more flexible this way

othman El moulat replied on Mon, 2011/07/11 - 11:37am

@Anton Arhipov

 

-if i navigate to : "http://localhost:8080/myservlet" it works. where "myservlet" is mapped to the servlet i want to invoke like: ctx.addServletMapping("/myservlet", "hello");

however if i simply navigate to the embeded tomcat root :  http://localhost:8080  it gives an error

"The requested resource () is not available."

which is not nice to have as error if the embeded tomcat server is started!

 -another issue i have is if i have a java staement after the last 2 lines :

 tomcat.start();

tomcat.getServer().await();

 it doesn't execute! it seems after invoking these two last lines no other java statement is executed. why is this? or am i doing something wrong?

thanks for the good post!

Anton Arhipov replied on Mon, 2011/07/11 - 12:36pm

I think the tomcat.getServer().await(); is a blocking call and that is fine. Why would you want to execute any statements after that? An option is to move the code into a separate Thread and start Tomcat from there, then you can add any code you like once the launching thread has been spawned.

othman El moulat replied on Mon, 2011/07/11 - 12:41pm

Great. thanks again for the very good post about embeded tomcat.

othman El moulat replied on Thu, 2011/08/11 - 7:05pm

Hello,

does embedded tomcat support comet servlets? i wrote a comet enabled servlet and added it to my Embedded tomcat configuration , but it seems when this comet servlet is requested it doesn't call the event() method.

any idea how to get comet work with embeded tomcat?

 

thanks.

Afkham Azeez replied on Sun, 2011/10/16 - 12:42am

Take a look at http://blog.afkham.org/2011/09/embedding-tomcat-7-bettertomcat.html. This blogpost provides code segments which show how simple it is to embed Tomcat 7

Avri Shpigel replied on Tue, 2012/06/19 - 1:31pm

Dear Anton,I am using embed tomcat 7.0.27 inside my java code.I have minimal tomcat config as proposed here.I would like to add images via html command <img src="aaa.gif" />Also I would like to have index.jsp file to reply when accessing my homepage. 
My question is: what is the additional minimal tomcat config requred to define the path where to put my images?
Very thanks you in advanceAvri 

Misgana Bayetta replied on Mon, 2014/04/07 - 7:22am

 Tomcat.addServlet(context, name, servlet)  this also seems to work. I found it in this part  of oryx and the how to spawn is found in the Runner.java.

Monkeyq Spanker replied on Sat, 2014/08/23 - 1:21pm

Can you please provide an example of embedded tomcat clustering?

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.