1.IntroductionThe 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. 2.Download Jetty?Before we can start creating our project, we need to download any stable version of Jetty JARs fromJetty@eclipse downloads site. In this article, I have used Jetty 7. The per Jetty site comes with following bundle.
3.Create an Eclipse Project?You just need to follow the below mentioned steps to create a Java project in Eclipse.
As our project is now setup, we are ready to create our web application which is going to be launched within our application. 4.Create a Web Application?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"?>
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.
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns="http://java.sun.com/xml/ns/j2ee" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <welcome-file-list> <welcome-file>page/index.jsp</welcome-file> </welcome-file-list> </web-app> <%@ page language="java" contentType="text/html;
charset=ISO-8859-1 pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Embedding Jettye</title> </head> <body> <h2>Running Jetty web server from our application!!</h2> </body> </html> 5.Create a Jetty Server Instance?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;
Once we created WebAppContext; we create a class which is responsible to manipulateorg.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.
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"); webAppContext.setResourceBase("."); webAppContext.setContextPath("/runJetty"); return webAppContext; } } 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() { this(8585); } public JettyServer(Integer runningPort) { server = new Server(runningPort); } public void setHandler(ContextHandlerCollection contexts) { server.setHandler(contexts); } public void start() throws Exception { server.start(); } public void stop() throws Exception { server.stop(); server.join(); } public boolean isStarted() { return server.isStarted(); } public boolean isStopped() { return server.isStopped(); } } 6.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. package blog.runjetty.ui.listener;
Once the ActionListener has been created, we need to create a JFrame. Our ServerRunner classextends JFrame. It has a JButton, which has been registered to ServerStartStopActionListner to perform start or stop oparation when clicked.
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; } @Override public void actionPerformed(ActionEvent actionEvent) { JButton btnStartStop = (JButton) actionEvent.getSource(); if(jettyServer.isStarted()){ btnStartStop.setText("Stopping..."); btnStartStop.setCursor(new Cursor(Cursor.WAIT_CURSOR)); try { jettyServer.stop(); } catch (Exception exception) { exception.printStackTrace(); } btnStartStop.setText("Start"); btnStartStop.setCursor (new Cursor(Cursor.DEFAULT_CURSOR)); } else if(jettyServer.isStopped()){ btnStartStop.setText("Starting..."); btnStartStop.setCursor(new Cursor(Cursor.WAIT_CURSOR)); try { jettyServer.start(); } catch (Exception exception) { exception.printStackTrace(); } btnStartStop.setText("Stop"); btnStartStop.setCursor (new Cursor(Cursor.DEFAULT_CURSOR)); } } } package blog.runjetty.ui;
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.
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"); setDefaultCloseOperation(EXIT_ON_CLOSE); btnStartStop = new JButton("Start"); btnStartStop.addActionListener (new ServerStartStopActionListner(jettyServer)); add(btnStartStop,BorderLayout.CENTER); setSize(300,300); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { if(jettyServer.isStarted()) { try { jettyServer.stop(); } catch (Exception exception) { exception.printStackTrace(); } } } },"Stop Jetty Hook")); setVisible(true); } } 7.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;
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:
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(); jettyServer.setHandler(contexts); Runnable runner = new Runnable() { @Override public void run() { new ServerRunner(jettyServer); } }; EventQueue.invokeLater(runner); } } 8.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.
9.Explain Jetty Embedded Hello World Application?We used to deploy our application in server. In some cases, we need to deploy server in our application. In this post, I am going to explain you, how to deploy Jetty in your application. <dependency>
<groupId>org.eclipse.jetty</groupId> <artifactId>jetty-server</artifactId> <version>9.3.4.RC1</version> </dependency> 10.HelloWorld.java?import java.io.IOException; public class HelloWorld extends AbstractHandler {
Run above application and hit the url ‘http://localhost:8080/’ in browser. You will get following output.@Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html; charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println(" Welcome to Jetty Application");baseRequest.setHandled(true); } public static void main(String[] args) throws Exception { Server server = new Server(8080); server.setHandler(new HelloWorld()); server.start(); server.join(); } } Welecome to Jetty Application server.start(); server.join(); Above statements create and run an HTTP server on port 8080. If you don’t set any handlers to this server, then it returns 404-error message for every request. public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) target: Represents the target of the request, usually it is an URI. baseRequest: Jetty mutable request object request: Immutable request object, can be wrapped by a filter or servlet. response: response send to user, can be wrapped by a servlet/filter. server.setHandler(new HelloWorld()); Once we add the handler to server instance, it can able to handle HTTP requests. 11.?
12.?
13.?
14.?
15.?
16.?
17.?
18.?
19.?
20.?
|