Click here to Skip to main content
13,050,896 members (63,871 online)
Click here to Skip to main content
Add your own
alternative version


24 bookmarked
Posted 16 Nov 2010

Run Jetty Web Server Within Your Application

, 18 Nov 2010
Rate this:
Please Sign up or sign in to vote.
Don't deploy your application in Jetty, deploy Jetty in your application



The purpose of this article is to give you a quick idea of how to build and deploy your web application without really running a web server outside your application and without creating a WAR file for the deployment. At present, I am working on a project which is a background calculation engine and it provides a simple web interface for the support and business users to monitor the ongoing activities. While deploying our application, we just start Jetty web server within our application and we can access the web application easily.

If you visit the Jetty wiki, it is mentioned that Jetty has a slogan, "Don't deploy your application in Jetty, deploy Jetty in your application." In this article, we illustrate this slogan in a nice and simple application.

Download Jetty

Before we can start creating our project, we need to download any stable version of Jetty JARs from Jetty@eclipse downloads site. In this article, I have used Jetty 7. The per Jetty site comes with following bundle.

  • Core Jetty Web Server (HTTP & Websocket)
  • Core Jetty Servlet Container
  • JNDI, JMX, OSGi, JASPI modules
  • HTTP Client

Apart from Jetty JAR, we need to have JSK 1.6 and Eclipse 3.5 installed on our system. Once these three things are ready, then we are good to create our application.

Create an Eclipse Project

You just need to follow the below mentioned steps to create a Java project in Eclipse.

  • Go to Eclipse's File menu and create a Java project.
  • Keep the default JRE option if it is selected as JavaSE-1.6.
  • Click the Library tab and select the Jetty Jar files.
  • Once the project has been created, add two more folders in your project "page" and "WEB-INF".

Once we are done with the creation of project, the project structure should look like the following diagram:


As our project is now setup, we are ready to create our web application which is going to be launched within our application.

Create a Web Application

  1. Create a deployment descriptor (i.e. web.xml) in WEB-INF folder. This is a very basic descriptor only welcome file name is mentioned within it.
     <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.4"
  2. Next we need to create an index.jsp page within page folder, which is going to be displayed when we hit the URL in our web browser.
    <%@ page language="java" contentType="text/html; 
    charset=ISO-8859-1 pageEncoding="ISO-8859-1"%> 
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
    		<meta http-equiv="Content-Type" 
    			content="text/html; charset=ISO-8859-1">
    		<title>Embedding Jettye</title>
    		<h2>Running Jetty web server from our application!!</h2>

Create a Jetty Server Instance

  1. First, we build a WebAppContext in which we can define location of our deployment descriptor and set the application context path. This WebAppContext required to set the header of Jetty server which will be illustrated in a later part of this section. The following code describes how to build WebAppContext.
    package blog.runjetty.context;
    import org.eclipse.jetty.webapp.WebAppContext;
    public class AppContextBuilder {
    	private WebAppContext webAppContext;
    	public WebAppContext buildWebAppContext(){
    		webAppContext = new WebAppContext();
    		webAppContext.setDescriptor(webAppContext + "/WEB-INF/web.xml");
    		return webAppContext;
  2. Once we created WebAppContext; we create a class which is responsible to manipulate org.eclipse.jetty.server.Server class's instance. For this, I have built a wrapper JettyServer. It defines the running post (default 8585), sets context header (i.e. setting the WebAppContext), starts/stops the server and checks whether the server is running or not.
    package blog.runjetty.server;
    import org.eclipse.jetty.server.Server;
    import org.eclipse.jetty.server.handler.ContextHandlerCollection;
    public class JettyServer {
    	private Server server;
    	public JettyServer() {
    	public JettyServer(Integer runningPort) {
    		server = new Server(runningPort);
    	public void setHandler(ContextHandlerCollection contexts) {
    	public void start() throws Exception {
    	public void stop() throws Exception {
    	public boolean isStarted() {
    		return server.isStarted();
    	public boolean isStopped() {
    		return server.isStopped();

Create a User Interface to Start and Stop Server

Now we are going to build a simple swing based user interface which has a start/stop button. Depending on the server status, it either starts the server or turns it off.
  1. Create an ActionListener which actually checks the current status of the server and toggles its state whenever any action is performed. In our application, we have created ServerStartStopActionListner which implements ActionListener interface and overrides actionPerformed method.
    package blog.runjetty.ui.listener;
    import java.awt.Cursor;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import blog.runjetty.server.JettyServer;
    public class ServerStartStopActionListner implements ActionListener {
    	private final JettyServer jettyServer;
    	public ServerStartStopActionListner(JettyServer jettyServer) {
    		this.jettyServer = jettyServer;
    	public void actionPerformed(ActionEvent actionEvent) {
    		 JButton btnStartStop =  (JButton) actionEvent.getSource();
    			 btnStartStop.setCursor(new Cursor(Cursor.WAIT_CURSOR));
    			 try {
    			} catch (Exception exception) {
    				(new Cursor(Cursor.DEFAULT_CURSOR));
    		 else if(jettyServer.isStopped()){
    			 btnStartStop.setCursor(new Cursor(Cursor.WAIT_CURSOR));
    			 try {
    			} catch (Exception exception) {
    				(new Cursor(Cursor.DEFAULT_CURSOR));
  2. Once the ActionListener has been created, we need to create a JFrame. Our ServerRunner class extends JFrame. It has a JButton, which has been registered to ServerStartStopActionListner to perform start or stop oparation when clicked.
    package blog.runjetty.ui;
    import java.awt.BorderLayout;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import blog.runjetty.server.JettyServer;
    import blog.runjetty.ui.listener.ServerStartStopActionListner;
    public class ServerRunner extends JFrame{
    	private static final long serialVersionUID = 8261022096695034L;
    	private JButton btnStartStop;
    	public ServerRunner(final JettyServer jettyServer) {
    		super("Start/Stop Server");
    		btnStartStop = new JButton("Start");
    			(new ServerStartStopActionListner(jettyServer));
    		Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
    			public void run() {
    				if(jettyServer.isStarted()) {
    					try {
    					} catch (Exception exception) {
    		},"Stop Jetty Hook")); 
  3. In ServerRunner, I have added a ShutdownHook. So, whenever the user clicks on the close button on the top right corner of the window, it will first check whether the server is running or not. If running, it will stop the server before exiting.

Create a Main Method

Now once everything is ready, we are good to create a main method which triggers the user interface. The following code shows how to launch the interface.
package blog.runjetty.main;

import java.awt.EventQueue;

import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;

import blog.runjetty.context.AppContextBuilder;
import blog.runjetty.server.JettyServer;
import blog.runjetty.ui.ServerRunner;

public class JettyFromMain {

	public static void main(String[] args) {
		ContextHandlerCollection contexts = new ContextHandlerCollection();
		contexts.setHandlers(new Handler[] 
			{ new AppContextBuilder().buildWebAppContext()});
		final JettyServer jettyServer = new JettyServer();
		Runnable runner = new Runnable() {
			public void run() {
				new ServerRunner(jettyServer);

Here you can find that I am fist creating ContextHandlerCollection and adding our WebAppContext and later setting the handler into our server. In the run() method, I am creating an instance of ServerRunner. After the following implementation, our project structure should look like the following diagram:


Run the Application

It's time now to test our application. Perform the following actions step by step to run the application and find out for yourself how it works.

  1. Run the application from Eclipse.
  2. You should see the following window:


  3. Click on Start button. Wait until the text of the button changes to Stop as mentioned in the diagram below:


  4. Open a web browser and hit the URL as http://localhost:8585/runJetty/.
    Your web application should be up and running as demonstrated in the figure below:


  5. Now, click the Stop button or close the window directly.
  6. If you click on the Stop button, wait for text appears as Start. Then refresh your browser window to verify that your web application is not running anymore as shown below:

    web_application_not_running.png - Click to enlarge image


As you have seen, it is easy to build and deploy Jetty server in our application. Now you are ready to explore on your own, like creating a SSL connection with just a few lines of codes, build a more complex web application using Spring MVC or any other Java web technology. For more information, please visit the official Jetty web site: or feel free to post your comments here. Any suggestions or advice is always welcome!


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Bikash Shaw
Software Developer (Senior) Société Générale
India India

1. Extensive working experience in web and windows application development, database programming using Java and .Net technologies.

2. Good knowledge in SDLC and Processes like project planning, requirement gathering, development, test planning, release management and production support.

3. Good knowledge and working experience in following methodologies:
a. Agile Development Approach
b. Test Driven Development
c. Behavior Driven Development
d. Continuous Integration & Delivery Model.

4. Excellent communication & analytical skills, good team player, great mentoring capability.

5. Interaction with customer and team spread over different geographical area.

Technologies / Languages: J2SE 5/6, J2EE, .Net 2.0/3.5, C#, ASP.NET, AJAX, XHTML, CSS, JavaScript, jQuery, PL/SQL, Web Services (SOAP based), Winforms, Hibernate, Spring, GWT, XML, XSD, XPath, SAX, JAXB, JUnit, JBehave, Mockito, Selenium, StringTemplate, Log4J, Apache Commons API

Database: Oracle, SQL Server, MySQL, Sybase

Application Server: Tomcat, Sun Application Server, JBoss, GlassFish, Jetty, IIS

Development Environments: Eclipse, NetBeans, Visual Studio.

Designing Tools: Enterprise Architect, Microsoft Visio

Version Control: SVN, Perforce

Build Management: Hudson & JCruisemonitor, TeamCity

Bug Tracking Tools: HP Quality Center, Bugzilla, JIRA

1. Agile Test and Behavior Driven Development
2. Continuous Delivery Approach
2. Spring IOC and MVC
3. Web Services

You may also be interested in...


Comments and Discussions

QuestionNice Pin
Alessandro Mattiuzzi6-Oct-15 0:02
memberAlessandro Mattiuzzi6-Oct-15 0:02 
Questionfull jdk issue Pin
Member 112849023-Dec-14 22:06
memberMember 112849023-Dec-14 22:06 
QuestionUnable to redirect from JSP to Servlet Pin
Ashis Panigrahi6-Oct-14 22:26
memberAshis Panigrahi6-Oct-14 22:26 
Questiongreat example, but I have a problem Pin
Luke Griffiths28-Dec-13 23:57
memberLuke Griffiths28-Dec-13 23:57 
QuestionExcellent, thank you Pin
rokhead19-Aug-13 18:12
memberrokhead19-Aug-13 18:12 
QuestionHow to achieve the same in Netbeans? Pin
Member 47733365-Apr-13 1:02
memberMember 47733365-Apr-13 1:02 
Hi! I want to achieve the same thing in Netbeans please post some suggesstions.
QuestionWhy use an embedded server like Jetty? Pin
Sridhar Balasubramanian24-Nov-12 0:30
memberSridhar Balasubramanian24-Nov-12 0:30 
QuestionPlease guys Pin
tuzzo779-Jul-12 23:24
membertuzzo779-Jul-12 23:24 
QuestionSample not working Pin
shasi sekar23-Jan-12 21:50
membershasi sekar23-Jan-12 21:50 
AnswerRe: Sample not working Pin
George Jempty24-Jan-12 8:08
memberGeorge Jempty24-Jan-12 8:08 
GeneralRe: Sample not working Pin
Member 902645824-May-12 17:33
memberMember 902645824-May-12 17:33 
GeneralGreat Starting Example! Pin
gcstang18-Nov-10 12:03
membergcstang18-Nov-10 12:03 
AnswerRe: Great Starting Example! Pin
Bikash Shaw22-Nov-10 6:58
memberBikash Shaw22-Nov-10 6:58 
GeneralMy vote of 5 Pin
César de Souza17-Nov-10 14:33
memberCésar de Souza17-Nov-10 14:33 
GeneralRe: My vote of 5 Pin
Bikash Shaw17-Nov-10 23:37
memberBikash Shaw17-Nov-10 23:37 
GeneralMy vote of 5 Pin
HoyaSaxa9316-Nov-10 21:55
memberHoyaSaxa9316-Nov-10 21:55 
GeneralRe: My vote of 5 Pin
Bikash Shaw16-Nov-10 22:03
memberBikash Shaw16-Nov-10 22:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170713.1 | Last Updated 18 Nov 2010
Article Copyright 2010 by Bikash Shaw
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid