Tomcat embedded + add servlet

Hi,
I need to use Tomcat in an embedded mode. No problem to do this. The only problem is that I want to have a servlet added to the server at startup coding it directly in my start method. I have saw that it is possible with Jetty, is it possible too with Tomcat ?
Thanks.

Hi,
download the Tomcat "Embedded" version at http://tomcat.apache.org/download-55.cgi and try the following code:
import org.apache.catalina.*;
import org.apache.catalina.connector.*;
import org.apache.catalina.realm.*;
import org.apache.catalina.startup.*;
import org.apache.catalina.users.*;
public class EmbeddedTomcat
  // Instance variables:
  private String    name;
  private int       portNumber;
  private Embedded  embedded;
  private Engine    baseEngine;
  private Host      baseHost;
  private Connector httpConnector;
  /** Creates a new instance of EmbeddedTomcat */
  public EmbeddedTomcat(
    String name,
    int    portNumber)
    this.name = name;
    this.portNumber = portNumber;
    init();
  private void init()
    MemoryRealm realm;
    Context     context;
    String      baseEngineName;
    String      hostName;
    embedded = new Embedded();
    // set default logger and realm
       FileLogger fileLog = new FileLogger();
       fileLog.setDirectory(".");
       fileLog.setPrefix(name);
       fileLog.setSuffix(".log");
       fileLog.setTimestamp(true);
       embedded.setLogger(fileLog);
    realm = new MemoryRealm();
    embedded.setRealm(realm);
    // create an Engine
    baseEngine = embedded.createEngine();
    // set Engine properties
    baseEngineName = name + "Engine";
    hostName = name + "Host";
    baseEngine.setName(baseEngineName);
    baseEngine.setDefaultHost(hostName);
    baseHost = embedded.createHost(hostName, "webapps");
    baseEngine.addChild(baseHost);
    // RootContext
    context = addContext("", "ROOT");
    // ManagerContext
    context = addContext("/manager", "manager");
    context.setPrivileged(true);
    // add new Engine to set of Engine for embedded server
    embedded.addEngine(baseEngine);
    // create Connector
    httpConnector = embedded.createConnector((java.net.InetAddress) null,
        portNumber, false);
    // add new Connector to set of Connectors for embedded server, associated
    // with Engine
    embedded.addConnector(httpConnector);
  public void start()
    // start server
    try
      embedded.start();
    catch (org.apache.catalina.LifecycleException ex)
      ex.printStackTrace();
      //fileLog.log("Startup failed");
      //fileLog.log(ex.getMessage());
  public Context addContext(
    String path,
    String docBase)
    Context c;
    c = embedded.createContext(path, docBase);
    baseHost.addChild(c);
    return c;
  public static void main(String[] args)
    new EmbeddedTomcat("test", 8080).start();
}Let me know if you have any problems.
/klejs

Similar Messages

  • Tomcat server add on the device

    Hi Folks,
    Can anyone tell me the exact location of the jscpout.txt file so that  i can check
    whether the Tomcat server add on has been successfully installed or not.
    Can you please clarify :
    I have downloaded the tomcat addon from the sapnote 1009703 but it is a zipfile.
    I am looking for the file MAP70_WinCESetupTomcat_Tomcat.CAB file.
    Though i have copied the add on to the device using Active sync.
    The client installer has been created on my pc and again i try to
    find the tomcat cab file but i can see only the txt file.
    Can you suggest how to get the tomcat cab file and how to run on the device.
    And the location of the jscpout.txt file so that i can check the tomcat
    installation successful or not.
    Thanks,
    Aswini

    Hi Aswini
        The jscpout.txt file is present in the root folder of the PDA (i.e directly under \ ).  The tomcat addon that is attached to note 1009703 will only be zip fie and not a cab file since this needs to be installed only after you have successfully installed MAP70_WinCESetupTomcat_Tomcat.CAB which is nothing but the MI JSP client installer for PDA. So the steps are as below
    1. Install Creme JVM (Creme 3.27A)
    2. Install MAP70_WinCESetupTomcat_Tomcat.CAB.
    3. Sync to obtain a device id.
    4. Upload and assign tomcat addon to the device.  The steps for this is mentioned in note 1009703 itself.
    Hope this helps.
    Best Regards
    Sivakumar

  • How do I get the Tomcat port using Servlet.

    I am running Apache + Tomcat. All request are going though Apache. How do I get the Tomcat port using Servlet.

    See:
    ServletRequest.getServerPort()This will give the port upon which the request was recieved . . .which I blelieve is what you are looking for.

  • How can i avoid restarting tomcat server when servlet is modified?

    please advice me that how can i avoid restarting the tomcat server, whenever a servlet file is modified in my application. is their any way ?

    No probs. Here's how I do things...
    1. Install tomcat as normal (e.g. I install to C:\Apps\jakarta-tomcat-5.5.4)
    2. Create a webapps directory in your eclipse project with the following directory structure
    MyEclipseProject
       - src
       - conf
       - webapps
          - MyApplication
             - META-INF
             - WEB-INF
                - classes
                - lib
                - pages3. Set the project's output folder (e.g. bin folder) to webapps/MyApplication/WEB-INF/classes
    4. Put all your jar files in the lib directory
    5. Put JSPs / HTML in the pages directory (you may also want to create additional directories for TLDs, config files etc)
    6. Ensure your web.xml is in the WEB-INF directory
    7. Although it isn't essential I create a context.xml file and store it in META-INF, e.g.
    <Context reloadable="true">
        <!-- Default set of monitored resources -->
         <WatchedResource>WEB-INF/web.xml</WatchedResource>
         <WatchedResource>WEB-INF/conf/struts/struts-config.xml</WatchedResource>
         <WatchedResource>WEB-INF/conf/struts/tiles-defs.xml</WatchedResource>
         <WatchedResource>WEB-INF/conf/struts/validation.xml</WatchedResource>     
    </Context>I use this to set monitored resources that will trigger an automatic appliation reload and to configure JAAS (not shown). See the Tomcat documentation for additional information.
    8. In the 'conf' directory I create a server.xml file used to configure Tomcat (you can copy the one from your <TOMCAT_HOME>/conf/server.xml).
    After copying the file change appBase attribute in the host element to be the full path to the webapps directory. You can also change the HTTP and HTTPS ports if you wish
    9. Download and install the Tomcat Launcher plugin from Sysdeo.
    10. In Eclipse's Preferences menu you will see a new entry for Tomcat. Click this then
    a. Set your Tomcat Version
    b. Set your Tomcat Home
    c. Set "Context declaration mode" to server.xml
    d. Set the configuration file to the full path to your server.xml file created in step 8
    On the "Advanced " sub page select all relevant projects to add to the Tomcat classpath
    On the "JVM Settings" page add all the jars in your WEB-INF lib directory to the class path
    On the "Source Path" page select all relevant projects
    Now if you start Tomcat using the Tomcat icon, you will be able to remote debug your application. If you change web.xml (or any other file in your context.xml watched resources) it will automatically reload. Any changes to JSPs will automatically be picked up (providing your tell your browser not to use the page in cache - e.g. CTRL+F5 in IE)
    There are some limitations that I'm still working on however. Primarily that I haven't included the Tomcat Manager application in my webapps directory, so Sysdeo cannot perform a reload. This means that if I change a source file, and eclipse auotmatically rebuilds, Tomcat doesn't pick up the change unless I either change a watched resource file (e.g. web.xml) or stop and restart Tomcat.
    There's no reason why this can't be fixed, I just haven't got round to it yet.
    I'm sure there are lots of other (probably better) ways of achieving the same thing. This was the first method I tried and it worked, so I stuck with it. I'm not a Tomcat config guru and I'm sure other forum users could provide some improvements should they wish.
    Post if you get into trouble, however I won't be able to respond until next week.
    Cheers,
    Steve

  • Web.xml Tomcat 5.0 Servlet problem

    Hey guys....
    The last time I used a servlet was before the new change in security in Tomcat. Ive been looking all over the net for some easy references about how they are to be mapped but no matter what I try nothing seems to work.
    My servlet is located in ROOT\Admin\WEB-INF\classes\colt and is called AddOLO.class
    My web.xml file is located in ROOT\Admin\WEB-INF and contains the following code:
    <servlet>
    <servlet-name>AddOLO</servlet-name>
    <servlet-class>colt.AddOLO</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>AddOLO</servlet-name>
    <url-pattern>/Admin/add</url-pattern>
    </servlet-mapping>
    On the HTML form invoking the Servlet (addOLO.html) Im using the following small piece of code
    <form action="http://Colt/Admin/servlet/AddOLO" method="post" align="centre">
    The server is operating on Port 80.
    All I seem to be getting is a 404 Error Saying The requested resource (/Admin/servlet/AddOLO) is not available. Can anyone see what is wrong here?
    Thanks in advance

    I don't think there's anything to prohibit you from deploying servlets in ROOT, but webapps that have pages and servlets that work together should be in their own context. That's what you did when you created the directory under webapps. I think it's the right way to deploy web apps. Even better, learn how to create and deploy WAR files:
    http://access1.sun.com/techarticles/simple.WAR.html
    Once you have a WAR, which is simply a JAR'd version of the directory you just created under webapps, you can simply pick it up and deploy it by dropping it into the webapps directory of any Tomcat server. Tomcat will unpack it for you. - MOD

  • Tomcat, LDAP, SSL, Servlet

    Hi - I have already written a servlet that binds against a LDAP Server normally. Now I need to implement SSL on it. I would like to know if anyone has any code that simply binds against an LDAP Server using SSL.
    I use the servlet on Tomcat to connect to the LDAP Server .. so...
    1. Do I need to install JSSE alongwith Tomcat to use ssl?
    2. Since the servlet acts as the Client to the LDAP Server - is it enough to simply add ssl parameters to the code (and include a cert store path)?
    I would only require to know simple steps to ssl-enable my existing application ...
    please help!

    I had problems getting SSL to work. The only modifications that you should need to make are in the connection.
    Here is the URL.
    http://forum.java.sun.com/thread.jsp?forum=51&thread=322566

  • Tomcat & Embedded()

    I am having a problem transferring my webapp from my development Jbuilder6 IDE with integrated TomCat 4.0 to a non integrated version of Tomcat 4.0.
    I am using a servlet that runs on startup that uses the Embedded class to build an an engine and multiple hosts. Within the JBullder environment this works fine, but when I to run it outside of JBuilder Tomcat will run only part of the servlet. The servlet stops running at the line Embedded embedded = newEmbedded().
    For example:
    public void init() throws ServletException {
    System.out.println("here1");
    System.setProperty("catalina.home","C:/EmbeddedTomcat");
    Embedded embedded = new Embedded();
    System.out.println("here2");
    will output only 'here1' in the tomcat console.
    I am new to catalina development so any help with this problem would be greatly appreciated.
    Thanks in advance.

    I may be out of line here but you probably could get this to work...it would be a bit of a hack job but it is possible.
    With regards to your "NoClassDefFound" problem (and adding dynamic contexts) I believe your problem is that there is a rarely used var that you can set in server.xml that allows the user to access the main Tomcat jars. The main Tomcat classes are separated from the webapp specific classes on startup...i.e. loaded completely separately and access is closed off for security. The var I mentioned changes this.
    Unfortunately, it's been a while since I was reading up on this so I completely forget the name of it....it's some type of "Factory" object/var that exposes the JARs you need.
    Once you get access to the other side of Tomcat, then you "should" be able to use the main JARs to dynamically reload contexts and webapps using the same methods and classes tomcat itself uses to start.
    I would guess that to develop this into a production capable solution would take quite some time....but who knows
    ON THE LOG ISSUE......something to note...check out the /logs directory and see if your System.out.println() calls are being fed to the logs....tomcat seems to like making this the stdout as opposed to the console...which is reasonnable considering most production versions won't have the error logs piped to the screen :)
    Hope some of this helps...like I said..it's been a while since I've looked into this so I could be wrong.
    RG

  • How to Add Servlet at portal root?

    Hi experts,
    I want to add a new servlet at portal root, which can be called like
    http://<host>:<port>/myservlet?parameter1=1&Parameter2=2
    I have created a web module and deployed by a web application to portal
    Web Module : "WebM" have servlet "Webcall".  and servlet "Webcall" have 2 parameter P1 and P2.
    Now I can call the servlet using URL:     http://<host>:<port>/WebM/Webcall?P1=1&P2=2
    But I need http://<host>:<port>/Webcall?P1=1&P2=2
    How can I do to get that result???
    Thanks a lot for help.
    Ned

    Hi Ned.
    Search SCN for key words URL Aliases.
    Best regards,
    Aliaksandr Zhukau

  • Tomcat 4.0,Servlet 2.3 and JSP1.2

    Trying to figure out what to do with the Servlet 2.3 and JSP 1.2 zip files. Have the JDK 1.4 and Tomcat 4.0 already installed. Cant find any instructions at all on the java website on where to unzip the classes. JDK1.4/lib?Thanks in advance.

    Thanks for the reply. So then where do the javax.* classes reside? How does the servlet.java file find the imported servlet classes when the pgm is compiled? Why is java such a PITA to get up and running? Sorry. I keep getting:
    A Servlet Exception Has Occurred
    org.apache.jasper.JasperException: Unable to compile class for JSPNote: sun.tools.javac.Main has been deprecated.
    if (pageContext != null) pageContext.handlePageException(t);
    when I try to run a .jsp with tomcat.

  • LocateRegistry.getRegistry() fails when called from Tomcat 5.5 servlet

    I'm trying to access a simple RMI server from a Tomcat 5.5 (Java 5) servlet. I get access exceptions having to do with java.util.logging.LoggingPermission. (The RMI server works fine with a simple command line Java app.)
    Is there some reason that calling getRegistry() from within a servlet should fail? Is there some reason that it should require LoggingPermission?
    I've modified the catalina.policy file to grant all permission to everything but I still get the same errors.
    Surely there is a way to make RMI calls from a servlet. Any suggestions on how to fix this? Thanks.

    show us the script

  • Restart tomcat at every servlet modify?

    Hi,
    I'm using tomcat 5.5 and working on some servlets, but when I execute a servlet (http://localhost/my_servlet)
    and then I modify and recompile it, I have to shutdown and restart tomcat to see the new version on work.
    Is this normal? Can I avoid this?
    Thanx

    Well, I have solved the problem editing contex.wml file modifying the line:
    <Context>into the line:
    <Context reloadable="true">Now it works even if refresh time is not so low...
    Thanx to all.
    P.S.
    Adding the line
    <DefaultContext reloadable="true"/>into server.xml file I don't have obtained any result.

  • Regarding TOmcat Restart evertime servlet is modified

    Hi,
    Myself Ashwin MIttal, using Tomcat on the Linux and Windows OS. Hey I am developing servlet and when I deploy servlet each time. I have to restart the Tomcat ....
    Is there anyway to solve the problem means There is no need to restart the Tomcat when eber serlvet is modified..
    Regards,
    Ashwin Mittal.

    In the context, type reloadable="true"yup, this is a better option.But you want to only do this on your developement machine. reloadable contexts take up a lot of resources, every x amount of time, the server has to check the classpath directories for modified time. Even if you don't make changes, this takes up resources. So once you move from development to deployment you want to turn this off...

  • How to attach a file to tomcat server using SERVLETS

    Hello friends,
    I want to enable users to attach a file and send it to my server. This is a very common feature seen anywhere like e-mail attachments.
    Iam using tomcat server. I tried HTTP put but it did not work.
    Please give some suggessions.
    Thanks
    Goldy

    check this url:
    http://www.servlets.com/cos/index.html
    follow the link MultiPartRequest
    Spieler

  • Tomcat: reloading modified servlets?

    hi
    in tomcat it's possible to configure a servlet context to automaticaly reload if the servlet was rebuild. i know how to do that and i works.
    what i want to change is the reation time of tomcat. it sometimes takes quite a long time till tomcat realizes that a servlet has changed and reloads it. I think that mechnism is quite simple, kind of a thread that looks for a new modifed date of the servlet file and reloads or not and goes to sleep again for a amount of time. My question: is there a possibility to configurate that parameter that handels the sleep time?
    thanx for your help!

    If you get hold of the source (this is from v4.0.4)
    Look in org.apache.cataline.loader.StandardLoader.java
    you will see at line 164 that this value has a hard coded default of 15 (seconds).
    There is a public void setCheckInterval(int checkInterval) but I'm not sure where you can configure this to be set - I can't find any classes which call it.
    It might be possible to access the loader from a servlet run at start up with an init() method that sets a new value.
    HH

  • Where to place HTMl files in  tomcat while executing Servlets examples ?

    Hi,
    I'm learning servelets (HttpServlets). in that input is given through html files.now i dont know where to place that html file in apache tomcat server
    This is my Directry Structure
    Java's ---- C:\Program Files\Java\jdk1.5.0\bin
    Tomcat's--C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class ThreeParams extends HttpServlet
    public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "Reading Three Request Parameters";
    String docType ="<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +"Transitional//EN\">\n";
    out.println(docType +"<HTML>\n" +"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +"<BODY BGCOLOR=\"#FDF5E6\">\n" +"<H1 ALIGN=\"CENTER\">" + title + "</H1>\n" +"<UL>\n" +" <LI><B>param1</B>: "+ request.getParameter("param1") + "\n" +" <LI><B>param2</B>: "+ request.getParameter("param2") + "\n" +" <LI><B>param3</B>: "+ request.getParameter("param3") + "\n" +"</UL>\n" +"</BODY></HTML>");
    }HTML code ---
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <HTML><HEAD><TITLE>Collecting Three Parameters</TITLE></HEAD>
    <BODY BGCOLOR="#FDF5E6">
    <H1 ALIGN="CENTER">Collecting Three Parameters</H1>
    <FORM ACTION="ACTION="C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\root\WEB-INF\classes.ThreeParams">
    First Parameter: <INPUT TYPE="TEXT" NAME="param1"><BR>
    Second Parameter: <INPUT TYPE="TEXT" NAME="param2"><BR>
    Third Parameter: <INPUT TYPE="TEXT" NAME="param3"><BR>
    <CENTER><INPUT TYPE="SUBMIT"></CENTER>
    </FORM>
    </BODY></HTML>
    {code}
    servlet code is compiling without any errors, now where should i place the class file and html file in tomcat to execute this program..                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    webapps\yourapplicationname\WEB-INF\

Maybe you are looking for