BACK | INDEX | EXIT | NEXT

# Jetty Server

Introduction
The HttpServer class provides the core Jetty HTTP server and HttpHandler extension architecture. The org.mortbay.jetty and org.mortbay.jetty.servlet packages extend the basic HttpServer with standard compliant servlets and webapplications. The key classes in these packages are:

- org.mortbay.jetty.Server extends HttpServer with XML configuration and servlet conveniance methods.
- org.mortbay.jetty.servlet.ServletHandler A HttpHandler that uses standard servlets to provide dynamic content. Can be used in a HttpServer or as the basis of a Web Application.
- org.mortbay.jetty.servlet.ServletHttpContext extends HttpContext with conveniance methods for Servlets..
- org.mortbay.jetty.servlet.WebApplicationHandler extends ServletHandler with security and filtering capabilities.
- org.mortbay.jetty.servlet.WebApplicationContext extends ServletHttpContext with the ability to add and configure a WebApplicationHandler from a `WEB-INF/web.xml` file from within a standard web application.
- org.mortbay.jetty.servlet.Default The default servlet within a webapplication that serves static content. This servlet replaces ResourceHandler and NotFoundHandler when using webapplications.
- org.mortbay.jetty.servlet.Invoker A servlet for creating dynamic servlet mappings.

Using the ServletHandler If you do not wish to use web applications but you want to deploy servlets, then you need to register at least one context and at least the ServletHandler with the server. You are able to statically configure individual servlets at a specific URL pattern, or use dynamic mapping to extract servlet names from the request URL.

The ServletHandler can be used with a HttpServer:

    HttpServer server = new HttpServer();
    server.addListener(":8080");
    HttpContext context = server.getContext("/");
    ServletHandler handler= new ServletHandler();
    handler.addServlet("Dump","/dump/*",
                       "org.mortbay.servlet.Dump");
    context.addHandler(handler);
Code Example: Using ServletHandler in HttpServer

Alternately, the org.mortbay.jetty.Server can be used instead of a HttpServer, so that it's conveniance methods may be used:

    Server server = new Server();
    server.addListener(":8080");
    ServletHttpContext context = (ServletHttpContext)
        server.getContext("/");
    context.addServlet("Dump","/dump/*",
                       "org.mortbay.servlet.Dump");
Code Example: Using ServletHandler in Server

Using Static Servlet Mappings

The examples above used defined servlet mappings to map a request URL to a servlet. Prefix (eg "/dump/*"), suffix (eg. "*.jsp"), exact (eg "/path") or default ("/") mappings may be used and they are all within the scope of the context path:

    Server server = new Server();
    server.addListener(":8080");
    ServletHttpContext context = (ServletHttpContext)
        server.getContext("/context");
    context.addServlet("Dump","/dump/*",
                       "org.mortbay.servlet.Dump");
    context.addServlet("Dump","/dump/session",
                       "org.mortbay.servlet.SessionDump");
    context.addServlet("JSP","*.jsp",
                       "org.apache.jasper.servlet.JspServlet");
    context.addServlet("Default","/",
                       "org.mortbay.jetty.servlet.Default");
Code Example: Static servlet mappings

Examples of URLs that will be mapped to these servlets are:

`/context/dump` | Dump Servlet by prefix
`/context/dump/info` | Dump Servlet by prefix
`/context/dump/session` | SessionDump Servlet by exact
`/context/welcome.jsp` | JSP Servlet by suffix
`/context/dump/other.jsp` | Dump Servlet by prefix
`/context/anythingelse` | Default Servlet
`/anythingelse` | Not this context

Using Dynamic Servlets
Servlets can be discovered dynamically by using the org.mortbay.jetty.servlet.Invoker servlet. This servlet uses the request URI to determine a servlet class or the name of a previously registered servlet:

    Server server = new Server();
    server.addListener(":8080");
    ServletHttpContext context = (ServletHttpContext)
        server.getContext("/context");
    context.addServlet("Dump","/dump/*",
                       "org.mortbay.servlet.Dump");
    context.addServlet("Invoker","/servlet/*",
                       "org.mortbay.jetty.servlet.Invoker");
Code Example: Dynamic servlet mappings

Examples of URLs that will be mapped to these servlets are:

`/servlet/Dump` | Dump Servlet by name
`/servlet/com.acme.MyServlet/info` | Servlet by dynamic class
`/servlet/com.mortbay.servlet.Dump` | Dump Servlet by class or ERROR

By default, the Invoker will only load servlets from the context classloader, so the last URL above will result in an error. The Invoker can be configured to allow any servlet to be run, but this can be a secuirty issue.

Deploying Web Applications

The Servlet Specification details a standard layout for web applications. If your content is packaged according to these specifications, then simply call the `addWebApplication(...)`methods on the org.mortbay.jetty.Server instance, specifying at minimum a context path, the directory or `war` file of your application. Jetty is then able to discover and configure all the required handlers including security, static content and servlets.

The `addWebApplication(...)`methods transparently create and return an instance of WebApplicationContext which contains a WebApplicationHandler.

The WebApplicationHandler extends ServletHandler and as well as servlets, it provides standard security and filters. Normally it is configured by the `webdefault.xml` file to contain Invoker, JSP and Default servlets. Filters, Servlets and other mechanisms are configured from the `WEB-INF/web.xml` file within the web application.

This example configures a web application located in the directory `./webapps/myapp/` at the context path `/` for a virtual host `myhost`:

    server.addWebApplication("myhost","/","./webapps/myapp/");
Code Example: Configuring a web application

The arguments to the `addWebApplication` method are:

- An (optional) virtual host name for the context
- A context path
- The location of the web application, which may be a directory structure or a `war` file, given as a URL, war filename or a directory name.

The `addWebApplication` method is overloaded to accommodate the parameters marked as (optional).

Note: If you run Jetty within JBoss, then you should NOT use the addWebApplication API (or XML), as this bypasses the JBoss classloaders. Use the JBoss deployment mechanisms instead and only use the Jetty configuration for listeners and logs.

Multiple Web Applications
To make things even easier, if you have multiple web apps to deploy, you can accomplish this with a single method call:

`
    server.addWebApplications ("myhost","./webapps/");
` Code Example: Configuring multiple web apps

Given the code above, Jetty would look in the directory `"./webapps/"` for all `war` files and subdirectories, and configure itself with each web application specified therein. For example, assuming the directory `webapps` contained the `war` files `webapps/root.war, webapps/customer.war and webapps/admin.war`, then Jetty would create the contexts `"/"`, `"/customer/*"` and `"/admin/*"` mapped to the respective war files. NOTE the special mapping of `war` files (or directories) named `root` to the context `"/"`.
In order to actually deploy the web application, it is also necessary to configure a port listener. The full code example to deploy the web application in the code snippet is:

    Server server = new Server();
    SocketListener listener = new SocketListener();
    listener.setPort(8080);
    server.addListener(listener );
    server.addWebApplication("myhost","./webapps/myapp/");
    server.start();
Code Example: Deploying a web application

Using XML
The same web application can be deployed instead via an XML configuration file instead of calls to the API. The name of the file is passed to Jetty as an argument on the command line (see the section on Jetty demonstrations for instructions). The following excerpt deploys the same web application as given in the code example above:

    <Configure class="org.mortbay.jetty.Server">
      <Call name="addListener">
        <Arg>
          <New class="org.mortbay.http.SocketListener">
              <Set name="Port">
                <SystemProperty name="jetty.port"
                 default="8080"/>
              </Set>
          </New>
        </Arg>
      </Call>

      <Call name="addWebApplication">
        <Arg>/</Arg>
        <Arg><SystemProperty name="jetty.home"
              default="."/>/webapps/myapp
        </Arg>
      </Call>
     </Configure>
XML Example: Deploying a web application

An explanation of the Jetty XML syntax can be found in the section on Jetty XML Configuration.
Web Application Configuration
When a WebApplicationContext is started, up to three configuration files are applied as follows:

1. `webdefault.xml` This file must be in standard web.xml format and typically contains all the default settings for all webapplicatios. By default the `org/mortbay/jetty/servlet/webdefault.xml` file is used as a resource from the jetty jar and it configures the JspServlet and default session timeouts. The default xml file may be changed for a particular context by calling `setDefaultsDescriptor(String)`
2. `web.xml` The standard web application configuration file and is found in the `WEB-INF` directory of the webapplicaton.
3. `web-jetty.xml` This file must be in `org.mortbay.xml.XmlConfiguration` format and if found in the `WEB-INF`directory of a web application, it is applied to the `WebApplicationContext` instance. It is typically used to change non standard configuration.

       <Configure class="org.mortbay.jetty.servlet.WebApplicationContext">
           <Set name="statsOn" type="boolean">false</Set>
       </Configure>
   XML Example: A web-jetty.xml file

   Note: the name `jetty-web.xml` is also accepted for this file.

Web Application Security
Jetty makes the following interpretations for the configuration of security constraints within a web.xml file:

- Methods PUT, DELETE and GET are disabled unless explicitly enabled.
- If multiple security-constraints are defined, the most specific applies to a request.
- A security-constraint an empty auth-constraint forbids all access by any user:

  >         <security-constraint>
  >           <web-resource-collection>
  >            <web-resource-name>Forbidden</web-resource-name>
  >             <url-pattern>/auth/noaccess/*</url-pattern>
  >           </web-resource-collection>
  >           <auth-constraint/>
  >         </security-constraint>

- A security constraint with an auth constraint with a role of "*" gives access to all authenticated users:

  >         <security-constraint>
  >           <web-resource-collection>
  >             <web-resource-name>Any User</web-resource-name>
  >             <url-pattern>/auth/*</url-pattern>
  >           </web-resource-collection>
  >           <auth-constraint>
  >             <role-name>*</role-name>
  >           </auth-constraint>
  >         </security-constraint>

- A security-constraint with no auth-constraint and no data contrain gives access to any request:

  >         <security-constraint>
  >           <web-resource-collection>
  >             <web-resource-name>Relax</web-resource-name>
  >             <url-pattern>/auth/relax/*</url-pattern>
  >           </web-resource-collection>
  >         </security-constraint>

- On platforms without the / file separator or when the system parameter org.mortbay.util.FileResource.checkAliases is true, then the FileResouce class compares the absolutePath and canonicalPath and treats the resource as not found if they do not match. THIS means that win32 platforms need to exactly match the case of drive letters and filenames.
- Dynamic servlets by default, can only be loaded from the context classpath. Use ServletHandler.setServeDynamicSystemServlets to control this behaivour.

Security Recommendation
It is strongly recommended that secure WebApplications take following approach. All access should be denied by default with

>         <security-constraint>
>           <web-resource-collection>
>            <web-resource-name>Default</web-resource-name>
>             <url-pattern>/</url-pattern>
>           </web-resource-collection>
>           <auth-constraint/>
>         </security-constraint>

Specific access should then be granted with constraints like:

>       <security-constraint>
>         <web-resource-collection>
>           <url-pattern>/public/*</url-pattern>
>           <url-pattern>/images/*</url-pattern>
>           <http-method>GET</http-method>
>           <http-method>HEAD</http-method>
>         </web-resource-collection>
>         <web-resource-collection>
>           <url-pattern>/servlet/*</url-pattern>
>           <http-method>GET</http-method>
>           <http-method>HEAD</http-method>
>           <http-method>POST</http-method>
>         </web-resource-collection>
>         <auth-constraint>
>           <role-name>*</role-name>
>         </auth-constraint>
>       </security-constraint>

Session Security
Jetty uses the standard java.util.Random class to generate session IDs. This may be insufficient for high security sites. The SessionManager instance can be initialized with a more secure random number generator, such as java.security.SecureRandom The Jetty configuration XML to do this to a webapplication is:

>     <Call name="addWebApplication">
>       <Arg>/myapp/*</Arg>
>       <Arg><SystemProperty name="jetty.home"
>             default="."/>/demo/webapps/myapp</Arg>
>       <Call name="getServletHandler">
>         <Set name="sessionManager">
>           <New class="org.mortbay.jetty.servlet.HashSessionManager">
>             <Arg><New class="java.security.SecureRandom"/></Arg>
>           </New>
>         </Set>
>       </Call>
>     </Call>

Note: initialising the SecureRandom object is a one-off time consuming operation which may cause the initial request to take much longer.

BACK | INDEX | EXIT | NEXT