Thursday, October 11, 2012

Use Embedded Jetty to Create 'Executable' Web App


From Official Site:
Jetty provides an HTTP server, HTTP client, and javax.servlet container. These components are open source and available for commercial use and distribution.

Jetty is used in a wide variety of projects and products. Jetty can be embedded in devices, tools, frameworks, application servers, and clusters. See the Jetty Powered page for more uses of Jetty.


This post will talking about how to use embedded jetty to create an 'executable' web app --
double click on a batch file,
then the server started,
and then the browser is opened to a web page in that web app

You can find the binary distribution from official site (, all required jars are in it.

The Program

Config a jetty server and start it

package jetty;

import org.mortbay.jetty.Server;
import org.mortbay.jetty.webapp.WebAppContext;

 * start an embedded jetty server
public class JettyClass {
    public static void main(String[] args) throws Exception {
        // use 8080 port
        Server server = new Server(8080);

        WebAppContext context = new WebAppContext();

        // use relative path, start from project root
        // page address: http://localhost:8080/EmbeddingJettyTest



Just print some message when server startup to make sure web.xml works fine

package test;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

 * print message when server start,
 * to make sure web.xml works fine
public class TestListener implements ServletContextListener {

    public void contextDestroyed(ServletContextEvent arg0) {
        // TODO Auto-generated method stub

    public void contextInitialized(ServletContextEvent arg0) {
        // TODO Auto-generated method stub



Define the TestListener in it

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns=""
    <!-- add a listener to make sure this config file works -->


Use some scriptlet to output some message to make sure jsp works fine

<%@page contentType="text/html" pageEncoding="UTF-8"%>
        <meta http-equiv="Content-Type"
            content="text/html; charset=UTF-8">
        <!-- write some scriptlet to make sure jsp works -->
        <% String msg = "Hello World"; %>
        <%= msg %>


Execute the JettyClass and open browser (rem is keyword for comment)

rem /* define library folder */
set lib=.\lib
rem /* folder bin as classpath */
set NEWPATH=bin
rem /* for each *.jar in library folder, append it after classpath */
for %%1 in (%lib%\*.jar) do call :concat %%1

rem /* start chrome before server start */
start chrome http://localhost:8080/EmbeddingJettyTest/
rem /* Execute JettyClass */
java -Xmx128m -classpath %NEWPATH% jetty.JettyClass
goto :eof

rem /* sub function to append string */
goto :eof

The Result

View the demo flash on line


Embedding Jetty

batch file string concatenation


Demo flash

Full project is at github

No comments:

Post a Comment