Dashboard > Jetty > ... > Jetty Documentation > Embedding Jetty
Embedding Jetty Log In | Sign Up   View a printable version of the current page.

Added by Jan Bartel , last edited by Athena Yao on May 16, 2008  (view change) show comment
Labels: 
(None)

Contact the core Jetty developers at www.webtide.com
private support for your internal/customer projects ... custom extensions and distributions ... versioned snapshots for indefinite support ... scalability guidance for your apps and Ajax/Comet projects ... development services from 1 day to full product delivery

Embedding Jetty

Quick Start

Quick Start - Handlers

The following code implements an anonymous hello handler and starts a jetty server with it:

Handler handler=new AbstractHandler()
{
    public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch)
        throws IOException, ServletException
    {
        response.setContentType("text/html");
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().println("<h1>Hello</h1>");
        ((Request)request).setHandled(true);
    }
};

Server server = new Server(8080);
server.setHandler(handler);
server.start();

Quick Start - Servlets

Here is a simple example of embedding Jetty using a Hello world servlet:

Server server = new Server(8080);
Context root = new Context(server,"/",Context.SESSIONS);
root.addServlet(new ServletHolder(new HelloServlet("Ciao")), "/*");
server.start();

Quick Start - jetty.xml

You can programatically create a jetty Server, and still use a jetty.xml file to configure it:

Server server = new Server();
XmlConfiguration configuration = new XmlConfiguration(new File("myJetty.xml").toURL()); //or use new XmlConfiguration(new FileInputStream("myJetty.xml"));
configuration.configure(server);
server.start();

More Examples

These examples are all included as part of the standard Jetty distribution in the $JETTY_HOME/examples/embedded sub project.

  • FileServer - simple HTTP file server
  • OneHandler - Embed a single handler - useful when there is only a single simple source of content.
  • ManyHandlers - Embed multiple handlers, one called after the other on each request.
  • OneContext - An example of a handler within a context, which allows a contextPath, resourceBase and class loader to be set.
  • MinimalServlets - An example of a ServletHandler without a context.
  • OneServletContext - A servletHandler within a context, which has been constructed with a session handler.
  • ManyServletContexts - Multiple servlet contexts using context path to select the context.
  • LikeJettyXml - a code example that mimics the configuration of the standard jetty.xml file
  • FromXmlConfiguration - a example that shows how XML fragments may be used to build a server and/or context.

Setting up the classpath

To run Jetty you need only the following jars on the classpath:

  • servlet-api-2.5-6.x.jar
  • jetty-util-6.x.jar
  • jetty-6.x.jar

This gives you the capability to handle HTTP with handlers, servlets and webapplications.
Additional features such as JSP and AJP require additional jars (normally found in subdirectories of $JETTY_HOME/lib).

Java Server Pages

JSP2.1

Remember!

You need to use J2SE5 (aka jdk 1.5) if you wish to use JSP2.1.

This is the jsp version mandated by servlet specification 2.5. You will need these jars:

  • ant-1.6.5.jar
  • core-3.1.1.jar
  • jsp-2.1.jar
  • jsp-api-2.1.jar

JSP2.0

JSP 2.0 is used with version 2.4 of the servlet specification. Depending on the functionality you require, you may be able to use this version rather than the newer JSP2.1
These are the dependencies when JSP 2.0 is used:

  • ant-1.6.4.jar
  • jasper-compiler-5.5.15.jar
  • jasper-runtime-5.5.15.jar
  • jsp-api-2.0.jar
  • commons-el-1.0.jar
  • jcl104-over-slf4j-1.0-rc5.jar
  • slf4j-simple-1.0-rc5.jar
  • xmlParserAPIs-2.6.2.jar
  • xercesImpl-2.6.2.jar

I have written an open-source application that uses Jetty6 embedded:
 http://www.source-code.biz/ServletViewer/
Maybe this could be useful for others to get a start.

As long there is not tutorial you might want to have a look at: Quick Guide to Embedding Jetty

In the jetty.xml example, the argument for the XmlConfiguration constructor should be: new FileInputStream("myJetty.xml").

Clinton,

Thanks for pointing this out. Fixed now.

Jan

The example for MinimalServlets has an error.  It never calls:
handler.initialize();
HTH,
Tim

Tim, fixed in svn trunk. BTW the fix was in the ServletHandler class to ensure that the ServletHolders get initialized in the absence of any associated Context. Thanks for noticing this.

I have ported my application from Jetty5 to Jetty6 and while doing so I "discovered" a few things that I wish to share with all of you.

You can find the log and comments of it at the following

http://www.engidea.com/blog/informatica/jetty6/jetty6-explored.html

I hope you find it useful.

For my test rig, I found the examples provided in the links a bit confusing. I have an expanded, single webapp that I need to test. It has a web.xml that has specifications to set up Spring MVC, etc.

The good news is that, from the comments above, I found Christian's source very brief and understandable.  For my single-context test rig, I simplified even more:

 
        server = new Server();
        Connector connector = new SelectChannelConnector();
        connector.setPort(PORT);
        connector.setHost("127.0.0.1");
        server.addConnector(connector);

        WebAppContext wac = new WebAppContext();
        wac.setContextPath("/");
        wac.setWar("./web");    // this is path to .war OR TO expanded, existing webapp; WILL FIND web.xml and parse it
        server.setHandler(wac);
        server.setStopAtShutdown(true);

        server.start();

Consider adding an example which just does this most simple invocation.

 larry

I want to use Hessian protocol http://www.caucho.com/hessian/ between Server and Client. For server i need servlet container (Tomcat, Jetty...). I choose Jetty and write next code to realize Hessian Server into Jetty Embeded servlet container:

public class HessianServlet {
	public static void main(String[] args) throws Exception
	{
		Server server = new Server();
		Connector connector=new SocketConnector();
		connector.setPort(8888);

		server.setConnectors(new Connector[]{connector});
		ServletHandler handler=new ServletHandler();
		server.setHandler(handler);
		handler.addServletWithMapping("com.caucho.hessian.server.HessianServlet", "/hello");
		server.start();
		server.join();
	}
}

But i need to to pass 2 parameters for com.caucho.hessian.server.HessianServlet Servlet - this parameter i to pass over simple web.xml in simple deploy servlet:

<web-app>
  <servlet>
   <servlet-name>hello</servlet-name>
   <servlet-class>com.caucho.hessian.server.HessianServlet</servlet-class>
    <init-param>
      <param-name>home-class</param-name>
      <param-value>service.BasicService</param-value>
    </init-param>
    <init-param>
      <param-name>home-api</param-name>
      <param-value>service.Basic</param-value>
    </init-param>
  </servlet>

  <servlet-mapping>
    <url-pattern>/hello</url-pattern>
    <servlet-name>hello</servlet-name>
  </servlet-mapping>
</web-app>

How i can to pass this parameter for servlet over usual code (for example in my code in higher)???

For use of Jetty as an embedded container, where the full power of Servlets is not needed, ContextHandler is an extremely useful lightweight class. In particular it allows defining custom error handlers for the application.

Running Apache Axis in Embedded Jetty

import org.apache.axis.transport.http.AdminServlet;
import org.apache.axis.transport.http.AxisServlet;
import org.apache.log4j.Logger;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.security.SslSocketConnector;
import org.mortbay.jetty.servlet.Context;
import org.mortbay.jetty.servlet.ServletHolder;
 
...
 
server = new Server();
		SslSocketConnector sslConnector = new SslSocketConnector();
		sslConnector.setKeystore(KEYSTORE);
		sslConnector.setTruststore(KEYSTORE);
		sslConnector.setPassword(KEYPASSWORD);
		sslConnector.setKeyPassword(KEYPASSWORD);
		sslConnector.setTrustPassword(KEYPASSWORD);
		sslConnector.setMaxIdleTime(30000);
		sslConnector.setPort(443);
		server.addConnector(sslConnector);

		ServletHolder axisServletholder = new ServletHolder(new AxisServlet());
		ServletHolder axisAdminServletholder = new ServletHolder(
				new AdminServlet());

		Context root = new Context(server, "/", Context.SESSIONS);
		root.addServlet(axisServletholder, "/servlet/AxisServlet");
		root.addServlet(axisServletholder, "/services/*");
		root.addServlet(axisServletholder, "*.jws");
		root.addServlet(axisAdminServletholder, "/servlet/AdminServlet");

		try {
			log.info("Starting Web Container");
			server.start();
			//server.join();
		} catch (Exception e) {
			log.info("Error Starting Web Container", e);
			return;
		}

Also server-config.wsdd has to be in the classpath, i put it in the top level of my src jar. 

We've been using Jetty in an embedded application for over five years, but upon upgrading to 6.1.x it is now running in a separate JVM from the parent application, which is causing all sorts of headaches (e.g., we can't pass our own objects across the JVM boundary). Is there a way to force use of the same JVM as the parent app? We're currently using Jetty 6.1.5 with Java 5.

Thanks for any help! -- Ichiro Furusato

Hi

Is it possible to add servlets to a context when the server is running ?

Thanks 

Can someone help me put together an example of creating a URL rewriting handler in embedded mode? I need to have a URL like:

http://localhost:8080/groups/1234567

rewrite to

http://localhost:8080/groups/group?id=1234567

The "pattern" argument confuses me because it seems to be proprietary to Jetty vs. being based on regular expressions. I couldn't find documentation on this anywhere, and there are not many comments in the code.

Contact the core Jetty developers at www.webtide.com
private support for your internal/customer projects ... custom extensions and distributions ... versioned snapshots for indefinite support ... scalability guidance for your apps and Ajax/Comet projects ... development services from 1 day to full product delivery
Site running on a free Atlassian Confluence Open Source Project License granted to The Codehaus. Evaluate Confluence today.
Powered by Atlassian Confluence, the Enterprise Wiki. (Version: 2.6.2 Build:#919 Nov 26, 2007) - Bug/feature request - Contact Administrators