- GUI
- Windows API tutorial
- Introduction to Windows API
- Windows API main functions
- System functions in Windows API
- Strings in Windows API
- Date & time in Windows API
- A window in Windows API
- First steps in UI
- Windows API menus
- Windows API dialogs
- Windows API controls I
- Windows API controls II
- Windows API controls III
- Advanced controls in Windows API
- Custom controls in Windows API
- The GDI in Windows API
- PyQt4 tutorial
- PyQt5 tutorial
- Qt4 tutorial
- Introduction to Qt4 toolkit
- Qt4 utility classes
- Strings in Qt4
- Date and time in Qt4
- Working with files and directories in Qt4
- First programs in Qt4
- Menus and toolbars in Qt4
- Layout management in Qt4
- Events and signals in Qt4
- Qt4 Widgets
- Qt4 Widgets II
- Painting in Qt4
- Custom widget in Qt4
- The Breakout game in Qt4
- Qt5 tutorial
- Introduction to Qt5 toolkit
- Strings in Qt5
- Date and time in Qt5
- Containers in Qt5
- Working with files and directories in Qt5
- First programs in Qt5
- Menus and toolbars in Qt5
- Layout management in Qt5
- Events and signals in Qt5
- Qt5 Widgets
- Qt5 Widgets II
- Painting in Qt5
- Custom widget in Qt5
- Snake in Qt5
- The Breakout game in Qt5
- PySide tutorial
- Tkinter tutorial
- Tcl/Tk tutorial
- Qt Quick tutorial
- Java Swing tutorial
- JavaFX tutorial
- Java SWT tutorial
- wxWidgets tutorial
- Introduction to wxWidgets
- wxWidgets helper classes
- First programs in wxWidgets
- Menus and toolbars in wxWidgets
- Layout management in wxWidgets
- Events in wxWidgets
- Dialogs in wxWidgets
- wxWidgets widgets
- wxWidgets widgets II
- Drag and Drop in wxWidgets
- Device Contexts in wxWidgets
- Custom widgets in wxWidgets
- The Tetris game in wxWidgets
- wxPython tutorial
- Introduction to wxPython
- First Steps
- Menus and toolbars
- Layout management in wxPython
- Events in wxPython
- wxPython dialogs
- Widgets
- Advanced widgets in wxPython
- Drag and drop in wxPython
- Internationalisation
- Application skeletons in wxPython
- The GDI
- Mapping modes
- Creating custom widgets
- Tips and Tricks
- wxPython Gripts
- The Tetris game in wxPython
- C# Winforms Mono tutorial
- Java Gnome tutorial
- Introduction to Java Gnome
- First steps in Java Gnome
- Layout management in Java Gnome
- Layout management II in Java Gnome
- Menus in Java Gnome
- Toolbars in Java Gnome
- Events in Java Gnome
- Widgets in Java Gnome
- Widgets II in Java Gnome
- Advanced widgets in Java Gnome
- Dialogs in Java Gnome
- Pango in Java Gnome
- Drawing with Cairo in Java Gnome
- Drawing with Cairo II
- Nibbles in Java Gnome
- QtJambi tutorial
- GTK+ tutorial
- Ruby GTK tutorial
- GTK# tutorial
- Visual Basic GTK# tutorial
- PyGTK tutorial
- Introduction to PyGTK
- First steps in PyGTK
- Layout management in PyGTK
- Menus in PyGTK
- Toolbars in PyGTK
- Signals & events in PyGTK
- Widgets in PyGTK
- Widgets II in PyGTK
- Advanced widgets in PyGTK
- Dialogs in PyGTK
- Pango
- Pango II
- Drawing with Cairo in PyGTK
- Drawing with Cairo II
- Snake game in PyGTK
- Custom widget in PyGTK
- PHP GTK tutorial
- C# Qyoto tutorial
- Ruby Qt tutorial
- Visual Basic Qyoto tutorial
- Mono IronPython Winforms tutorial
- Introduction
- First steps in IronPython Mono Winforms
- Layout management
- Menus and toolbars
- Basic Controls in Mono Winforms
- Basic Controls II in Mono Winforms
- Advanced Controls in Mono Winforms
- Dialogs
- Drag & drop in Mono Winforms
- Painting
- Painting II in IronPython Mono Winforms
- Snake in IronPython Mono Winforms
- The Tetris game in IronPython Mono Winforms
- FreeBASIC GTK tutorial
- Jython Swing tutorial
- JRuby Swing tutorial
- Visual Basic Winforms tutorial
- JavaScript GTK tutorial
- Ruby HTTPClient tutorial
- Ruby Faraday tutorial
- Ruby Net::HTTP tutorial
- Java 2D games tutorial
- Java 2D tutorial
- Cairo graphics tutorial
- PyCairo tutorial
- HTML5 canvas tutorial
- Python tutorial
- Python language
- Interactive Python
- Python lexical structure
- Python data types
- Strings in Python
- Python lists
- Python dictionaries
- Python operators
- Keywords in Python
- Functions in Python
- Files in Python
- Object-oriented programming in Python
- Modules
- Packages in Python
- Exceptions in Python
- Iterators and Generators
- Introspection in Python
- Ruby tutorial
- PHP tutorial
- Visual Basic tutorial
- Visual Basic
- Visual Basic lexical structure
- Basics
- Visual Basic data types
- Strings in Visual Basic
- Operators
- Flow control
- Visual Basic arrays
- Procedures & functions in Visual Basic
- Organizing code in Visual Basic
- Object-oriented programming
- Object-oriented programming II in Visual Basic
- Collections in Visual Basic
- Input & output
- Tcl tutorial
- C# tutorial
- Java tutorial
- AWK tutorial
- Jetty tutorial
- Tomcat Derby tutorial
- Jtwig tutorial
- Android tutorial
- Introduction to Android development
- First Android application
- Android Button widgets
- Android Intents
- Layout management in Android
- Android Spinner widget
- SeekBar widget
- Android ProgressBar widget
- Android ListView widget
- Android Pickers
- Android menus
- Dialogs
- Drawing in Android
- Java EE 5 tutorials
- Introduction
- Installing Java
- Installing NetBeans 6
- Java Application Servers
- Resin CGIServlet
- JavaServer Pages, (JSPs)
- Implicit objects in JSPs
- Shopping cart
- JSP & MySQL Database
- Java Servlets
- Sending email in a Servlet
- Creating a captcha in a Servlet
- DataSource & DriverManager
- Java Beans
- Custom JSP tags
- Object relational mapping with iBATIS
- Jsoup tutorial
- MySQL tutorial
- MySQL quick tutorial
- MySQL storage engines
- MySQL data types
- Creating, altering and dropping tables in MySQL
- MySQL expressions
- Inserting, updating, and deleting data in MySQL
- The SELECT statement in MySQL
- MySQL subqueries
- MySQL constraints
- Exporting and importing data in MySQL
- Joining tables in MySQL
- MySQL functions
- Views in MySQL
- Transactions in MySQL
- MySQL stored routines
- MySQL Python tutorial
- MySQL Perl tutorial
- MySQL C API programming tutorial
- MySQL Visual Basic tutorial
- MySQL PHP tutorial
- MySQL Java tutorial
- MySQL Ruby tutorial
- MySQL C# tutorial
- SQLite tutorial
- SQLite C tutorial
- SQLite PHP tutorial
- SQLite Python tutorial
- SQLite Perl tutorial
- SQLite Ruby tutorial
- SQLite C# tutorial
- SQLite Visual Basic tutorial
- PostgreSQL C tutorial
- PostgreSQL Python tutorial
- PostgreSQL Ruby tutorial
- PostgreSQL PHP tutorial
- PostgreSQL Java tutorial
- Apache Derby tutorial
- SQLAlchemy tutorial
- MongoDB PHP tutorial
- MongoDB Java tutorial
- MongoDB JavaScript tutorial
- MongoDB Ruby tutorial
- Spring JdbcTemplate tutorial
- JDBI tutorial
Embedded Jetty
Jetty can be run in embedded mode. It means that it is not necessary to build a WAR file and deploy it in a standalone Jetty server. Jetty is a software component that can be instantiated and used just like any other POJO (Plain Old Java Object).
Simple handler
A Handler
is a component that deals with incoming requests. The requests are processed in the handle()
method. Handlers are passed the servlet API request and response object, but they are not servlets.
$ mkdir simplehandler $ cd simplehandler/ $ mkdir -p src/com/zetcode $ mkdir build $ touch src/com/zetcode/SimpleHandlerEx.java
We create a new project directory and its structure.
SimpleHandlerEx.java
package com.zetcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.AbstractHandler; public class SimpleHandlerEx extends AbstractHandler { @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/plain;charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); baseRequest.setHandled(true); response.getWriter().println("Hello there"); } public static void main(String[] args) throws Exception { Server server = new Server(8080); server.setHandler(new SimpleHandlerEx()); server.start(); server.join(); } }
A server is started and a handler is set for incoming requests.
response.setContentType("text/plain;charset=utf-8");
Since we only output simple text, we set the text/plain media type. An Internet media type is a standard identifier used on the Internet to indicate the type of data that a file contains.
response.getWriter().println("Hello there");
As a response, we send a simple message. The getWriter()
method returns a PrintWriter
object that sends character text to the client.
server.join();
The join()
method makes the server thread join with the current thread. It is blocking until server is ready. The method also waits until the server fully stops.
build.xml
<?xml version="1.0" encoding="UTF-8"?> <project name="SimpleHandlerEx" default="compile"> <property name="name" value="simplehandler"/> <property environment="env"/> <property name="src.dir" value="src"/> <property name="build.dir" value="build"/> <property name="jetty.lib.dir" location="${env.JETTY_HOME}/lib"/> <path id="compile.classpath"> <fileset dir="${jetty.lib.dir}"> <include name="**/*.jar"/> </fileset> </path> <path id="run.classpath"> <pathelement path="${build.dir}"/> <fileset dir="${jetty.lib.dir}"> <include name="**/*.jar"/> </fileset> </path> <target name="init"> <mkdir dir="${build.dir}"/> </target> <target name="compile" depends="init"> <javac srcdir="${src.dir}" destdir="${build.dir}" includeantruntime="false"> <classpath refid="compile.classpath"/> </javac> <echo>Compilation completed</echo> </target> <target name="run" depends="compile"> <echo>Running the program</echo> <java classname="com.zetcode.SimpleHandlerEx" classpathref="run.classpath"/> </target> <target name="clean" depends="init"> <delete dir="${build.dir}"/> <echo>Cleaning completed</echo> </target> </project>
The build file includes a run task, which executes the compiled application.
<property name="jetty.lib.dir" location="${env.JETTY_HOME}/lib"/>
To compile and run our examples, we need a handful of JARs. They are located in the lib/
subdirectory of the Jetty home.
$ ant run $ curl localhost:8080 Hello there
We receive this message when we send a simple GET request with the curl
application.
Defining the context root
The context root of a web application determines what URLs will be delegated to the application. Jetty has the ContextHandler
to define the application's context.
ContextEx.java
package com.zetcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.server.handler.ContextHandler; class MyHandler extends AbstractHandler { @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/plain;charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); baseRequest.setHandled(true); response.getWriter().println("Hello there"); } } public class ContextEx { public static void main(String[] args) throws Exception { Server server = new Server(8080); ContextHandler con = new ContextHandler(); con.setContextPath("/path"); con.setHandler(new MyHandler()); server.setHandler(con); server.start(); server.join(); } }
The handler of our application will be called for context root named /path
.
ContextHandler context = new ContextHandler(); context.setContextPath("/path");
A ContextHandler
is instantiated and a path is set.
context.setHandler(new MyHandler());
The handler is set for the context handler object.
server.setHandler(context);
We set the context handler object to the server with the setHandler()
method.
$ curl localhost:8080/path/ Hello there
We send the request to the defined context root. For non-matching contexts, Jetty returns the 404
error message.
Simple servlet
In the following example a Java servlet will be launched upon sending a request with a specific URL to the embedded Jetty.
$ mkdir simpleservlet $ cd simpleservlet/ $ mkdir -p src/com/zetcode/ $ touch src/com/zetcode/SimpleServlet.java $ touch src/com/zetcode/SimpleApp.java $ touch src/web/WEB-INF/web.xml $ touch build.xml
We create a project directory and its structure. We use Ant to build the project and a web.xml
deployment descriptor to configure our web application.
$ tree . ├── build.xml └── src ├── com │ └── zetcode │ ├── SimpleApp.java │ └── SimpleServlet.java └── web └── WEB-INF └── web.xml 5 directories, 4 files
At this moment these are the contents of the project directory.
SimpleApp.java
package com.zetcode; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.webapp.WebAppContext; public class SimpleApp { public static void main(String[] args) throws Exception { String webdir = "src/web/"; Server server = new Server(8080); WebAppContext wcon = new WebAppContext(); wcon.setContextPath("/simserv"); wcon.setDescriptor(webdir + "/WEB-INF/web.xml"); wcon.setResourceBase(webdir); wcon.setParentLoaderPriority(true); server.setHandler(wcon); server.start(); server.join(); } }
To configure our web application in the embedded mode, we utilize the WebAppContext
class. This class is an extension of the ContextHandler
that coordinates the construction and configuration of handlers for web applications.
wcon.setContextPath("/simserv");
A context path is defined with the setContextPath()
method.
wcon.setDescriptor(webdir + "/WEB-INF/web.xml");
The deployment descriptor is set with the setDescriptor()
method.
wcon.setResourceBase(webdir);
We set the document root for our application. It is a directory (or collection of directories or URL) that contains the static resources for the context. These can be images, HTML files, or JSP files.
SimpleServlet.java
package com.zetcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.*; public class SimpleServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/plain"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println("Simple servlet"); } }
The SimpleServlet
will respond with a plain text message.
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <servlet> <servlet-name>SimpleServlet</servlet-name> <servlet-class>com.zetcode.SimpleServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>SimpleServlet</servlet-name> <url-pattern>simple.do</url-pattern> </servlet-mapping> </web-app>
In the web.xml
file, the execution of the com.zetcode.SimpleServlet
is mapped to the simple.do
string. This has to be specified at the end of the request URL.
build.xml
<?xml version="1.0" encoding="UTF-8"?> <project name="SimpleServlet" default="compile"> <property name="name" value="simple"/> <property environment="env"/> <property name="src.dir" value="src"/> <property name="web.dir" value="${src.dir}/web"/> <property name="build.dir" location="${web.dir}/WEB-INF/classes"/> <property name="jetty.lib.dir" location="${env.JETTY_HOME}/lib"/> <path id="compile.classpath"> <fileset dir="${jetty.lib.dir}"> <include name="**/*.jar"/> </fileset> </path> <path id="run.classpath"> <pathelement path="${build.dir}" /> <fileset dir="${jetty.lib.dir}"> <include name="**/*.jar"/> </fileset> </path> <target name="init"> <mkdir dir="${build.dir}"/> </target> <target name="compile" depends="init"> <javac srcdir="${src.dir}" destdir="${build.dir}" includeantruntime="false"> <classpath refid="compile.classpath"/> </javac> <echo>Compilation completed</echo> </target> <target name="clean" depends="init"> <delete dir="${build.dir}"/> <echo>Cleaning completed</echo> </target> <target name="run" depends="compile"> <echo>Running the program</echo> <java classname="com.zetcode.SimpleApp" classpathref="run.classpath"/> </target> </project>
This is the accompanying Ant build file.
$ ant run $ curl localhost:8080/simserv/simple.do Simple servlet
We build and run the application. Sending a GET message to localhost:8080/simserv/simple.do
returns "Simple servlet" plain message.
The @WebServlet annotation
The @WebServlet
annotation is used to declare a servlet. The annotation is processed by the servlet container at deploy time. The declared servlet is available at the specified URL pattern.
$ tree . ├── build.xml └── src ├── com │ └── zetcode │ ├── AnnotatedAppEx.java │ └── MyServlet.java └── web └── WEB-INF 5 directories, 3 files
These are the contents of our project directory. In this example we do not include the web.xml
file, since with Servlet 3.1 API the inclusion of this file is optional.
AnnotatedAppEx.java
package com.zetcode; import org.eclipse.jetty.annotations.AnnotationConfiguration; import org.eclipse.jetty.plus.webapp.EnvConfiguration; import org.eclipse.jetty.plus.webapp.PlusConfiguration; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.webapp.Configuration; import org.eclipse.jetty.webapp.FragmentConfiguration; import org.eclipse.jetty.webapp.MetaInfConfiguration; import org.eclipse.jetty.webapp.WebAppContext; import org.eclipse.jetty.webapp.WebInfConfiguration; import org.eclipse.jetty.webapp.WebXmlConfiguration; public class AnnotatedAppEx { public static void main(String[] args) throws Exception { String webdir = "src/web/"; Server server = new Server(8080); WebAppContext wcon = new WebAppContext(); wcon.setResourceBase(webdir); wcon.setContextPath("/annotated"); wcon.setConfigurations(new Configuration[] { new AnnotationConfiguration(), new WebXmlConfiguration(), new WebInfConfiguration(), new PlusConfiguration(), new MetaInfConfiguration(), new FragmentConfiguration(), new EnvConfiguration() }); wcon.setParentLoaderPriority(true); server.setHandler(wcon); server.start(); server.join(); } }
This class starts an embedded Jetty server with annotations enabled.
wcon.setConfigurations(new Configuration[] { new AnnotationConfiguration(), new WebXmlConfiguration(), new WebInfConfiguration(), new PlusConfiguration(), new MetaInfConfiguration(), new FragmentConfiguration(), new EnvConfiguration() });
To enable annotations, we need to set these configuration classes. This gives support for multiple features.
MyServlet.java
package com.zetcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.*; @WebServlet(urlPatterns = { "/aserv" }) public class MyServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/plain"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println("MyServlet called"); } }
In the MyServlet.java
file we provide the @WebServlet
annotation. The servlet is available at the /aserv
url.
build.xml
<?xml version="1.0" encoding="UTF-8"?> <project name="AnnotatedServlet" default="compile"> <property name="name" value="annotated"/> <property environment="env"/> <property name="src.dir" value="src"/> <property name="web.dir" value="${src.dir}/web"/> <property name="build.dir" location="${web.dir}/WEB-INF/classes"/> <property name="jetty.lib.dir" location="${env.JETTY_HOME}/lib"/> <path id="compile.classpath"> <fileset dir="${jetty.lib.dir}"> <include name="**/*.jar"/> </fileset> </path> <path id="run.classpath"> <pathelement path="${build.dir}"/> <fileset dir="${jetty.lib.dir}"> <include name="**/*.jar"/> </fileset> </path> <target name="init"> <mkdir dir="${build.dir}"/> </target> <target name="compile" depends="init"> <javac srcdir="${src.dir}" destdir="${build.dir}" includeantruntime="false"> <classpath refid="compile.classpath"/> </javac> <echo>Compilation completed</echo> </target> <target name="clean" depends="init"> <delete dir="${build.dir}"/> <echo>Cleaning completed</echo> </target> <target name="run" depends="compile"> <echo>Running the program</echo> <java classname="com.zetcode.AnnotatedAppEx" classpathref="run.classpath"/> </target> </project>
This is the Ant build file for our project.
$ ant run $ curl localhost:8080/annotated/aserv MyServlet called
The MyServlet
was succesfully launched.
Enabling JavaServer Pages
In order to enable JavaServer Pages in the embedded Jetty mode, we need to create a temporary servlet directory, set a non-system classloader, add a jsp
servlet, and add a default
servlet.
In the following example, we create a simple JavaServer Page and build a WAR archive. This archive will be set to Jetty started in embedded mode.
$ pwd /home/janbodnar/prog/jetty/jspexample $ tree . ├── build.xml └── src ├── com │ └── zetcode │ └── JSPExample.java └── web ├── index.jsp └── WEB-INF 5 directories, 3 files
This is the project structure.
index.jsp
<!DOCTYPE html> <html> <body> <p> Today's date: <%= (new java.util.Date()).toLocaleString() %> </p> </body> </html>
Our JSP will output the current localized date.
package com.zetcode; import java.io.File; import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.List; import org.apache.jasper.servlet.JspServlet; import org.apache.tomcat.InstanceManager; import org.apache.tomcat.SimpleInstanceManager; import org.eclipse.jetty.annotations.ServletContainerInitializersStarter; import org.eclipse.jetty.apache.jsp.JettyJasperInitializer; import org.eclipse.jetty.plus.annotation.ContainerInitializer; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.DefaultServlet; import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.webapp.WebAppContext; public class JSPExample { private void startServer() throws Exception { String jetty_base = "/home/janbodnar/prog/jetty/my-base"; File tmpdir = new File(System.getProperty("java.io.tmpdir")); File scdir = new File(tmpdir.toString(), "embedded-jetty-jsp"); if (!scdir.exists()) { if (!scdir.mkdirs()) { throw new IOException("Unable to create scratch directory: " + scdir); } } Server server = new Server(8080); WebAppContext wcon = new WebAppContext(); wcon.setParentLoaderPriority(true); wcon.setContextPath("/"); wcon.setAttribute("javax.servlet.wcon.tempdir", scdir); wcon.setAttribute(InstanceManager.class.getName(), new SimpleInstanceManager()); server.setHandler(wcon); JettyJasperInitializer sci = new JettyJasperInitializer(); ServletContainerInitializersStarter sciStarter = new ServletContainerInitializersStarter(wcon); ContainerInitializer initializer = new ContainerInitializer(sci, null); List<ContainerInitializer> initializers = new ArrayList<>(); initializers.add(initializer); wcon.setAttribute("org.eclipse.jetty.containerInitializers", initializers); wcon.addBean(sciStarter, true); ClassLoader jspClassLoader = new URLClassLoader(new URL[0], this.getClass().getClassLoader()); wcon.setClassLoader(jspClassLoader); ServletHolder holderJsp = new ServletHolder("jsp", JspServlet.class); holderJsp.setInitOrder(0); holderJsp.setInitParameter("fork","false"); holderJsp.setInitParameter("keepgenerated", "true"); wcon.addServlet(holderJsp, "*.jsp"); ServletHolder holderDefault = new ServletHolder("default", DefaultServlet.class); holderDefault.setInitParameter("dirAllowed", "true"); wcon.addServlet(holderDefault, "/"); wcon.setWar(jetty_base + "/webapps/jspexample.war"); server.setHandler(wcon); server.start(); server.join(); } public static void main(String[] args) throws Exception { JSPExample ex = new JSPExample(); ex.startServer(); } }
We enable JSP support and set a WAR file called jspexample.war
to the web application context.
File tmpdir = new File(System.getProperty("java.io.tmpdir")); File scdir = new File(tmpdir.toString(), "embedded-jetty-jsp"); if (!scdir.exists()) { if (!scdir.mkdirs()) { throw new IOException("Unable to create scratch directory: " + scdir); } }
We create a scratch directory for the servlet context. It is used during JSP compilation.
System.setProperty("org.apache.jasper.compiler.disablejsr199","false");
This line forces to use standard javac. (There is also one used by Eclipse.)
JettyJasperInitializer sci = new JettyJasperInitializer(); ServletContainerInitializersStarter sciStarter = new ServletContainerInitializersStarter(wcon); ContainerInitializer initializer = new ContainerInitializer(sci, null); List<ContainerInitializer> initializers = new ArrayList<>(); initializers.add(initializer); wcon.setAttribute("org.eclipse.jetty.containerInitializers", initializers); wcon.addBean(sciStarter, true);
This is JSP initialization code.
ClassLoader jspClassLoader = new URLClassLoader(new URL[0], this.getClass().getClassLoader()); wcon.setClassLoader(jspClassLoader);
JSP require a non-System classloader, this simply wraps the embedded System classloader in a way that makes it suitable for JSP to use.
ServletHolder holderJsp = new ServletHolder("jsp", JspServlet.class); holderJsp.setInitOrder(0); holderJsp.setInitParameter("fork","false"); holderJsp.setInitParameter("keepgenerated", "true"); wcon.addServlet(holderJsp, "*.jsp");
We add a JspServlet
. Its name must be "jsp".
ServletHolder holderDefault = new ServletHolder("default", DefaultServlet.class); holderDefault.setInitParameter("dirAllowed", "true"); wcon.addServlet(holderDefault, "/");
We add a DefaultServlet
. Its name must be "default".
wcon.setWar(jetty_base + "/webapps/jspexample.war");
The WAR file is set to the web application context.
build.xml
<?xml version="1.0" encoding="UTF-8"?> <project name="JSPExample" default="compile"> <property name="name" value="jspexample"/> <property environment="env"/> <property name="src.dir" value="src"/> <property name="web.dir" value="${src.dir}/web"/> <property name="build.dir" location="${web.dir}/WEB-INF/classes"/> <property name="dist.dir" location="dist"/> <property name="jetty.lib.dir" location="${env.JETTY_HOME}/lib"/> <property name="jetty.base" location="${env.JETTY_BASE}"/> <property name="deploy.path" location="${jetty.base}/webapps"/> <path id="compile.classpath"> <fileset dir="${jetty.lib.dir}"> <include name="**/*.jar"/> </fileset> </path> <path id="run.classpath"> <pathelement path="${build.dir}"/> <fileset dir="${jetty.lib.dir}"> <include name="**/*.jar"/> </fileset> </path> <target name="init"> <mkdir dir="${build.dir}"/> <mkdir dir="${dist.dir}"/> </target> <target name="compile" depends="init"> <javac srcdir="${src.dir}" destdir="${build.dir}" includeantruntime="false"> <classpath refid="compile.classpath"/> </javac> <echo>Compilation completed</echo> </target> <target name="archive" depends="compile"> <war destfile="${dist.dir}/${name}.war" needxmlfile="false"> <fileset dir="${web.dir}"/> </war> <echo>Archive created</echo> </target> <target name="clean" depends="init"> <delete dir="${build.dir}"/> <delete dir="${dist.dir}"/> <echo>Cleaning completed</echo> </target> <target name="deploy" depends="archive"> <copy file="${dist.dir}/${name}.war" todir="${deploy.path}"/> <echo>Archive deployed</echo> </target> <target name="run" depends="deploy"> <echo>Running the program</echo> <java classname="com.zetcode.JSPExample" classpathref="run.classpath"/> </target> </project>
This is the Ant build for our project. All necessary jars are found in the lib subdirectory of the JETTY_HOME
directory.
Issuing ant run
leads to the following security exception: java.security.AccessControlException: access denied ("java.lang.RuntimePermission" "getClassLoader").
We need to add a configuration option to the java.policy
file.
$ vi $JAVA_HOME/jre/lib/security/java.policy
We edit the java.policy
file.
permission java.lang.RuntimePermission "getClassLoader", "read";
We add this permission.
$ ant run $ curl localhost:8080/index.jsp <!DOCTYPE html> <html> <body> <p> Today's date: Sep 16, 2014 1:54:05 PM </p> </body> </html>
The JSP returns the current date.
In this part of the Jetty tutorial, we have worked with Jetty in embedded mode. We have defined a simple handler and servlet, utilized a @WebServlet
annotation, and enabled JSP support.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论