This is intended to be the first post in a series on building straight-forward web-apps with Spring-MVC and embedded Jetty. You can check out the complete source of this simple project from github.

This post describes configuring your Jetty and Spring MVC with XML-based configuration. If you want to use annotations/java-config take a look at this post.

Its been a while since I last posted. I've been busy starting up two big projects at work, one using Google App Engine (and Spring MVC ;)), the other using Jetty 8 (embedded), Spring MVC, MongoDB and ElasticSearch.

The Jetty/Spring combination is one which I've used before - several times since Jetty-5/Spring-1.2 - and I really like. You just can't beat it for quick debug cycles, complete control of the environment, minimal configuration, single-jar deployment, etc., etc.

On this most recent project I'm using jsp as the view technology - this is probably the easiest way to go since most things "just work" out of the box. Other view technologies can be used too - for example last year we used this same combination with FreeMarker - its just a little more effort to get things wired up right.

Here's how I set my projects up:

Maven POM

<?xml version="1.0" encoding="UTF-8"?>


    <name>SpringSource Repository</name>






  <!-- JSP and JSTL SUPPORT -->


A couple of things worth pointing out:

  • I've added the spring-source maven repo in order to get the spring dependencies
  • I'm using Jetty 8 from eclipse, who have taken over from codehaus (who took over from mortbay)
  • I'm attaching sources for all dependencies that make them available, so that you can drill down into the source while debugging
  • I'm setting the source and target jdk compliance to 6
  • I'm using Jetty-jsp 8.1.4 - many other jstl implementations I tried have bugs, including a nasty one where recursive calls in tag-files would not compile.
  • I've never really bothered with things like maven archetypes, which is probably lazy-stupid of me. I tend to start from a pom that i've created previously then modify it to suit my needs.

After creating the pom in my project directory I create the src/main/java and src/test/java directories and then run mvn eclipse:eclipse to fetch the dependencies and create the eclipse .project and .classpath files. Having done that I import the project to Eclipse.

Once I have the project in Eclipse I create a few more directories - specifically the META-INF/webapp/WEB-INF directory to host my web.xml and spring context files (amongst other things).

I typically start with a spring application context and a spring web context, so I can specify beans at a larger scope than the web-application. Here's some simple example web and spring configs, all of which I place in WEB-INF:


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi=""
id="WebApp_ID" version="3.0">



<!-- Handles all requests into the application -->
    <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>

    <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>



<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

<!-- Define your application beans here. They will be available to the
   beans defined in your web-context because it is a sub-context.

   Beans defined in the web-context will not be available in the 
   application context.



<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

<!-- Configures the @Controller programming model -->

<!-- Forwards requests to the "/" resource to the "home" view -->
<mvc:view-controller path="/" view-name="index"/>    

<mvc:resources mapping="/i/**" location="WEB-INF/images/" />
<mvc:resources mapping="/c/**" location="WEB-INF/css/" />
<mvc:resources mapping="/s/**" location="WEB-INF/scripts/" />
<mvc:resources mapping="/favicon.ico" 
  location="WEB-INF/images/favicon.ico" />

<!-- Resolve jsp's -->
<bean id="viewResolver" 
    <property name="viewClass" 
    <property name="prefix" value="/WEB-INF/views/"/>
    <property name="suffix" value=".jsp"/>

<!-- i18n message source -->
<bean id="messageSource" 
    <property name="basename" value="/WEB-INF/i18n/messages" />
    <property name="defaultEncoding" value="UTF-8"/>
    <property name="cacheSeconds" value="30" />


Some important things to note in this file are:

  • We're using the annotation model for spring Controllers, hence there aren't any Controller beans specified in this xml
  • We're mapping static resources to be served efficiently by the Spring dispatcher servlet
  • We've set up a view resolver to look for jsp's in /WEB-INF/views. Note that when specifying a view in Controller code you drop the .jsp suffix.
  • We're configuring an internationalization message source, just so we can demonstrate use of a spring taglib a bit later...

Now we need to create a class to set up the embedded Jetty.

Embedded Jetty

package com.sjl;

import java.util.*;

import org.eclipse.jetty.server.*;
import org.eclipse.jetty.server.handler.*;
import org.eclipse.jetty.server.nio.*;
import org.eclipse.jetty.util.thread.*;
import org.eclipse.jetty.webapp.*;

 * Example WebServer class which sets up an embedded Jetty 
 * appropriately whether running in an IDE or in "production" 
 * mode in a shaded jar.
public class WebServer
    // TODO: You should configure this appropriately for 
    // your environment
    private static final String LOG_PATH = 

    private static final String WEB_XML = 
    private static final String CLASS_ONLY_AVAILABLE_IN_IDE = 
    private static final String PROJECT_RELATIVE_PATH_TO_WEBAPP = 

    public static interface WebContext
        public File getWarPath();
        public String getContextPath();

    private Server server;
    private int port;
    private String bindInterface;

    public WebServer(int aPort)
        this(aPort, null);

    public WebServer(int aPort, String aBindInterface)
        port = aPort;
        bindInterface = aBindInterface;

    public void start() throws Exception
        server = new Server();



    public void join() throws InterruptedException

    public void stop() throws Exception

    private ThreadPool createThreadPool()
        // TODO: You should configure these appropriately
        // for your environment - this is an example only
        QueuedThreadPool _threadPool = new QueuedThreadPool();
        return _threadPool;

    private SelectChannelConnector createConnector()
        SelectChannelConnector _connector = 
            new SelectChannelConnector();
        return _connector;

    private HandlerCollection createHandlers()
        WebAppContext _ctx = new WebAppContext();


        List&lt;Handler> _handlers = new ArrayList&lt;Handler>();


        HandlerList _contexts = new HandlerList();
        _contexts.setHandlers(_handlers.toArray(new Handler[0]));

        RequestLogHandler _log = new RequestLogHandler();

        HandlerCollection _result = new HandlerCollection();
        _result.setHandlers(new Handler[] {_contexts, _log});

        return _result;

    private RequestLog createRequestLog()
        NCSARequestLog _log = new NCSARequestLog();

        File _logPath = new File(LOG_PATH);

        return _log;

    private boolean isRunningInShadedJar()
            return false;
        catch(ClassNotFoundException anExc)
            return true;

    private URL getResource(String aResource)
        return Thread.currentThread().

    private String getShadedWarUrl()
        String _urlStr = getResource(WEB_XML).toString();
        // Strip off "WEB-INF/web.xml"
        return _urlStr.substring(0, _urlStr.length() - 15);

Notice that here we try to load a class that will only ever be available if we're running in test mode (e.g. directly from Eclipse).

If the class is found we assume we're running in exploded form, otherwise we assume we're running in a shaded jar - this is so that we can use the correct path to locate the web resources.

If you're trying this out you must make sure that the com.sjl.IDE class exists in your test source tree!.

Spring MVC Controller

package com.sjl.web;

import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.*;

public class Home {
    public ModelAndView home()
        return new ModelAndView("index");

A very simple Controller that simply tells Spring to render the index.jsp view when a request is made for the root of the web-app.


<%@taglib prefix="spring" uri=""%>
    <p><spring:message code="hello"/></p>


That's almost everything. You will need a couple of other little pieces, for example a main class to instantiate the WebServer.

Project directory structure

Your project directory structure should end up looking something like this:

|_____________[web.xml and spring context configs here]
|_______________[jsp files here]
|_____________[Spring MVC Controllers here]

Check out the github project for the complete working example.

blog comments powered by Disqus