- 浏览: 194603 次
- 性别:
- 来自: 武汉
文章分类
最新评论
-
shuaijie506:
以前有点疑惑,现在终于明白了,线程安全是没问题的,想想也是,如 ...
jsp自定义标签 线程安全 -
Laster2800:
原来如此,想不到传统的标记处理器也是线程安全的,受教了。
jsp自定义标签 线程安全 -
GoingForward:
这篇文章是不是可以浓缩为下面几点:1.在非静态内部类中不可以声 ...
static class -
wellse:
呵呵,就是这样!!要的就是这个效果
jsp自定义标签 线程安全 -
xiaohuafyle:
JNDI
Starting Jetty
To start Jetty open a command shell, go to your Jetty installation directory, and type:
java -jar start.jar
Jetty will not start if another process is using port 8080
The port number can be changed by editing the $JETTY_HOME/etc/jetty.xml file. Please see the #Setting Jetty's Port section below or for more details see How to Configure Jetty. The rest of the instructions in this wiki will assume that you are using port 8080
Contents[hide] |
Introduction
Jetty has a slogan "Don't deploy your application in Jetty, deploy Jetty in your application". What this means is that as an alternative to bundling your application as a standard WAR to be deployed in Jetty, Jetty is designed to be a software component that can be instantiated and used in a Java program just like any POJO.
This tutorial takes you step-by-step from the simplest Jetty server instantiation, to running multiple web applications with standards-based deployment descriptors.
The source for most of these examples is part of the standard Jetty project.
Details
To embed a Jetty server, the following steps are typical:
- Create the server
- Add/Configure Connectors
- Add/Configure Handlers
- Add/Configure Servlets/Webapps to Handlers
- start the server
- wait (join the server to prevent main exiting).
Servers
The following code from SimplestServer.java will instantiate and run the simplest possible Jetty server:
public class SimplestServer { public static void main(String[] args) throws Exception { Server server = new Server(8080); server.start(); server.join(); } }
This runs a HTTP server on port 8080. It is not a very useful server as it has no handlers and thus will return a 404 error for every request.
Handlers
In order to produce a response to a request, Jetty requires a Handler to be set on the server. A handler may:
- examine/modify the HTTP request.
- generate the complete HTTP response.
- call another Handler (see HandlerWrapper)
- Select one or many Handlers to call (see [ http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/server/handler/HandlerCollection.html HandlerCollection]
Hello World Handler
The following code based on HelloHandler.java shows a simple hello world handler:
public class HelloHandler extends AbstractHandler { 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); baseRequest.setHandled(true); response.getWriter().println("<h1>Hello World</h1>"); } }
The parameters passed to the handle method are:
- target - The target of the request which is either a URI or a name from a named dispatcher.
- baseRequest -The Jetty mutable request object, which is always unwrapped.
- request - The immutable request object, which may have been wrapped.
- response - The response that may have been wrapped.
The handler sets the response status, content-type and marks the request as handled before it generates the body of the response using a writer.
The following code from OneHandler.java shows how this handler can be used by a Jetty server:
public static void main(String[] args) throws Exception { Server server = new Server(8080); server.setHandler(new HelloHandler()); server.start(); server.join(); }
You now know everything you need to know to write a HTTP server based on Jetty. However, complex request handling is typically built from multiple Handlers and we will look in later sections how handlers can be combined like aspects. Some of the handlers available in Jetty can be seen in the org.eclipse.jetty.server.handler package.
Connectors
In order to configure the HTTP connectors used by the server, one or more Connectors may be set on the server. Each connector may be configured with details such as interface, port, buffer sizes, timeouts etc.
The following code is based on ManyConnectors.java and shows how connectors may be set and configured for the Hello World example:
public class ManyConnectors { public static void main(String[] args) throws Exception { Server server = new Server(); SelectChannelConnector connector0 = new SelectChannelConnector(); connector0.setPort(8080); connector0.setMaxIdleTime(30000); connector0.setRequestHeaderSize(8192); SelectChannelConnector connector1 = new SelectChannelConnector(); connector1.setHost("127.0.0.1"); connector1.setPort(8888); connector1.setThreadPool(new QueuedThreadPool(20)); connector1.setName("admin"); SslSelectChannelConnector ssl_connector = new SslSelectChannelConnector(); String jetty_home = System.getProperty("jetty.home","../jetty-distribution/target/distribution"); System.setProperty("jetty.home",jetty_home); ssl_connector.setPort(8443); ssl_connector.setKeystore(jetty_home + "/etc/keystore"); ssl_connector.setPassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4"); ssl_connector.setKeyPassword("OBF:1u2u1wml1z7s1z7a1wnl1u2g"); server.addConnector(ssl_connector); server.setConnectors(new Connector[]{ connector0, connector1, ssl_connector }); server.setHandler(new HelloHandler()); server.start(); server.join(); } }
Handler Collections, Wrappers and Scopes
Complex request handling is typically built from multiple Handlers that can be combined in various ways:
- A Handler Collection holds a collection of other handlers and will call each handler in order. This is useful for combining statistics and logging handlers with the handler that generates the response.
- A Handler List is a Handler Collection that calls each handler in turn until either an exception is thrown, the response is committed or the request.isHandled() returns true. It can be used to combine handlers that conditionally handle a request.
- A Handler Wrapper is a handler base class that can be use to daisy chain handlers together in the style of aspect-oriented programming. For example, a standard web application is implemented by a chain of a context, session, security and servlet handlers.
- A Context Handler Collection uses the longest prefix of the request URI (the contextPath) to select a specific ContextHandler to handle the request.
File Server
The following code from FileServer.java uses a HandlerList to combine the ResourceHandler with the DefaultHandler:
public class FileServer { public static void main(String[] args) throws Exception { Server server = new Server(); SelectChannelConnector connector = new SelectChannelConnector(); connector.setPort(8080); server.addConnector(connector); ResourceHandler resource_handler = new ResourceHandler(); resource_handler.setDirectoriesListed(true); resource_handler.setWelcomeFiles(new String[]{ "index.html" }); resource_handler.setResourceBase("."); HandlerList handlers = new HandlerList(); handlers.setHandlers(new Handler[] { resource_handler, new DefaultHandler() }); server.setHandler(handlers); server.start(); server.join(); } }
The resource handler is passed the request first and looks for a matching file in the local directory to serve. If a file is not found, then the request is passed to the default handler which will generate a 404 (or favicon.ico).
File Server with XML
Now is a good time to remind you that the Jetty XML configuration format is able to render simple Java code into XML configuration. So the above FileServer example can be written with a little reordering in Jetty XML as follows:
<?xml version="1.0"?> <!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure.dtd"> <Configure id="FileServer" class="org.eclipse.jetty.server.Server"> <Call name="addConnector"> <Arg> <New class="org.eclipse.jetty.server.nio.SelectChannelConnector"> <Set name="port">8080</Set> </New> </Arg> </Call> <Set name="handler"> <New class="org.eclipse.jetty.server.handler.HandlerList"> <Set name="handlers"> <Array type="org.eclipse.jetty.server.Handler"> <Item> <New class="org.eclipse.jetty.server.handler.ResourceHandler"> <Set name="directoriesListed">true</Set> <Set name="welcomeFiles"> <Array type="String"><Item>index.html</Item></Array> </Set> <Set name="resourceBase">.</Set> </New> </Item> <Item> <New class="org.eclipse.jetty.server.handler.DefaultHandler"> </New> </Item> </Array> </Set> </New> </Set> </Configure>
This XML file can be run from the FileServerXml.java class:
public class FileServerXml { public static void main(String[] args) throws Exception { Resource fileserver_xml = Resource.newSystemResource("fileserver.xml"); XmlConfiguration configuration = new XmlConfiguration(fileserver_xml.getInputStream()); Server server = (Server)configuration.configure(); server.start(); server.join(); } }
File Server with spring
The Spring framework can also be used to assemble jetty servers. The file server example above can be written in spring configuration as:
<beans> <bean id="Server" class="org.eclipse.jetty.server.Server" init-method="start" destroy-method="stop"> <property name="connectors"> <list> <bean id="Connector" class="org.eclipse.jetty.server.nio.SelectChannelConnector"> <property name="port" value="8080"/> </bean> </list> </property> <property name="handler"> <bean id="handlers" class="org.eclipse.jetty.server.handler.HandlerList"> <property name="handlers"> <list> <bean class="org.eclipse.jetty.server.handler.ResourceHandler"> <property name="directoriesListed" value="true"/> <property name="welcomeFiles"> <list> <value>index.html</value> </list> </property> <property name="resourceBase" value="."/> </bean> <bean class="org.eclipse.jetty.server.handler.DefaultHandler"/> </list> </property> </bean> </property> </bean> </beans>
See also the Jetty Spring HOWTO.
Contexts
A ContextHandler is a HandlerWrapper that will respond only to requests that have a URI prefix that match the configured context path.
Requests that match the context path will have their path methods updated accordingly and the following optional context features applied as appropriate:
* A Thread Context classloader. * A set of attributes * A set init parameters * A resource base (aka document root) * A set of virtual host names
Requests that don't match are not handled.
The following code is based on OneContext.java and sets context path and classloader for the hello handler:
public class OneContext { public static void main(String[] args) throws Exception { Server server = new Server(8080); ContextHandler context = new ContextHandler(); context.setContextPath("/hello"); context.setResourceBase("."); context.setClassLoader(Thread.currentThread().getContextClassLoader()); server.setHandler(context); context.setHandler(new HelloHandler()); server.start(); server.join(); } }
Servlets
Servlets are the standard way to provide application logic that handles HTTP requests. Servlets are like constrained Handlers with standard ways to map specific URIs to specific servlets. The following code is based on HelloServlet.java:
public class HelloServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println("<h1>Hello World</h1>"); response.getWriter().println("session=" + request.getSession(true).getId()); } }
ServletContext
A ServletContextHandler is a specialization of ContextHandler with support for standard servlets. The following code from OneServletContext shows 3 instances of the helloworld servlet registered with a ServletContextHandler:
public class OneServletContext { public static void main(String[] args) throws Exception { Server server = new Server(8080); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); server.setHandler(context); context.addServlet(new ServletHolder(new HelloServlet()),"/*"); context.addServlet(new ServletHolder(new HelloServlet("Buongiorno Mondo")),"/it/*"); context.addServlet(new ServletHolder(new HelloServlet("Bonjour le Monde")),"/fr/*"); server.start(); server.join(); } }
Web Application Context
A Web Applications context is a specialization of ServletContextHandler that uses the standard layout and web.xml to configure the servlets, filters and other features:
public class OneWebApp { public static void main(String[] args) throws Exception { String jetty_home = System.getProperty("jetty.home",".."); Server server = new Server(8080); WebAppContext webapp = new WebAppContext(); webapp.setContextPath("/"); webapp.setWar(jetty_home+"/webapps/test.war"); server.setHandler(webapp); server.start(); server.join(); } }
Context Handler Collection
A Context Handler Collection uses the longest prefix of the request URI (the contextPath) to select a specific context. The following example combines the previous two examples in a single Jetty server:
public class ManyContexts { public static void main(String[] args) throws Exception { Server server = new Server(8080); ServletContextHandler context0 = new ServletContextHandler(ServletContextHandler.SESSIONS); context0.setContextPath("/ctx0"); server0.setHandler(context); context0.addServlet(new ServletHolder(new HelloServlet()),"/*"); context0.addServlet(new ServletHolder(new HelloServlet("Buongiorno Mondo")),"/it/*"); context0.addServlet(new ServletHolder(new HelloServlet("Bonjour le Monde")),"/fr/*"); WebAppContext webapp = new WebAppContext(); webapp.setContextPath("/ctx1"); webapp.setWar(jetty_home+"/webapps/test.war"); ContextHandlerCollection contexts = new ContextHandlerCollection(); contexts.setHandlers(new Handler[] { context0, webapp }); server.setHandler(contexts); server.start(); server.join(); } }
相关推荐
本篇文章将深入介绍Jetty的基础知识,包括其核心概念、工作原理以及如何入门使用。 首先,Jetty的核心特性之一是它的轻量化设计。与其他重量级的Web服务器(如Apache Tomcat)相比,Jetty没有繁重的依赖,这使得它...
【Jetty入门学习资料】 Jetty是一个轻量级、高性能的开源Servlet容器,它由Java编写,以JAR包形式提供API,便于开发者将其轻松集成到Java应用中。Jetty自1995年创立以来,已被众多知名项目如Apache Geromino、JBoss...
本文将深入探讨Jetty的入门实例,帮助你快速掌握如何使用Jetty来运行简单的Web应用。 首先,让我们理解什么是Servlet。Servlet是Java编程语言中的一个接口,由Java Servlet API提供,它允许开发人员扩展Web服务器的...
本教程将引导你入门Jetty的使用,帮助你快速理解如何配置和运行Jetty服务器。 一、Jetty简介 Jetty是由Eclipse基金会维护的一个开源项目,它符合Java Servlet和JSP规范。与其他Web服务器相比,Jetty以其小型化、...
Jetty入门(视频) 下载和安装Jetty 如何安装一个Jetty包 如何配置Jetty – 主要文档 如何运行Jetty 用JConsole监控Jetty 如何使用Jetty开发 Jetty HelloWorld教程 Jetty和Maven HelloWorld教程 Jetty(6)入门 ...
在这个简单的Jetty入门示例中,你可能会学到如何创建一个简单的Servlet,如何处理HTTP GET和POST请求,以及如何通过Jetty API或配置文件来启动和停止服务器。此外,还会涉及如何使用Jetty的嵌入式模式,即直接在应用...
jetty快速入门与嵌入使用,简单、易懂,轻松学习!
资源名称:Jetty6入门教程资源截图: 资源太大,传百度网盘了,链接在附件中,有需要的同学自取。
- 《Jetty6入门教程.doc》可能是关于如何安装、配置和使用Jetty 6版本的文档,涵盖了基础概念、启动流程、部署Web应用等内容。Jetty 6是较早的版本,尽管现在推荐使用更新的版本,但对于理解Jetty的基本工作原理和...
#### 一、Jetty简介与入门 ##### 1.1 Jetty是什么? Jetty是一款开源的、轻量级的Java Web服务器和Java Servlet容器,由Eclipse基金会维护。它以其小巧、灵活、高性能的特点而著称,适用于开发测试环境和生产环境...
对于初学者,理解Jetty的基本结构和配置方式,以及如何通过它来部署和运行Servlet应用,是入门的关键。而对于有经验的开发者,深入研究Jetty的源码和模块化设计,可以帮助优化性能,实现更高效的应用服务。
该包适用于maven新手入门,因为作者本身也是一员maven新手,里面包括了maven的下载包,插件包,插件的配置,环境变量的设置,maven项目建立的详解及运行,里面集成了jetty,tomcat,struts2,当然还包括了直接运行jar包...
使用 Maven、Jetty 和 Jersey 的入门代码 使用 maven-shade-plugin 构建一个带有依赖项的胖 jar 使用单一资源在 8080 上运行码头服务器 建造 安装 跑步 java -jar target/jetty-app-{{version}}.jar 测试资源
这个"maven+spring+jetty+logback简单项目源码"提供了一个基础框架,方便新手快速入门并实践这些技术。 首先,`Maven`是Apache开发的一个项目管理和综合工具,它通过一个项目对象模型(Project Object Model, POM)...
### Wicket 入门与 Eclipse 项目创建指南 在当今的 Web 开发领域,Java 框架扮演着举足轻重的角色,其中 Apache Wicket 是一个强大的、面向组件的 Java Web 应用框架,它简化了 Web 应用的开发过程。本文将详细介绍...
此外,内嵌的Tomcat或Jetty服务器使得部署更简单。 接下来是Spring Boot的配置。配置文件主要有两种:`application.properties`和`application.yml`,两者功能相同,只是格式不同。这里你可以定义应用的基本属性,...
SpringBoot内置了Tomcat或Jetty服务器,只需一行命令即可启动应用。 **6. 自动配置** SpringBoot的一大亮点是自动配置。它根据项目依赖自动配置相应的Bean,减少了大量手动配置的工作。例如,如果项目引入了Spring...
3. **内嵌Web服务器**:Spring Boot可以内嵌Tomcat、Jetty等Web服务器,使得打包后的应用可以直接运行,无需额外部署到外部服务器。 4. **健康检查与Actuator**:Spring Boot提供Actuator模块,用于监控和管理应用...
Spring Boot 提供了内置的Tomcat或Jetty服务器,使得开发人员可以直接运行应用程序而无需额外配置外部容器。此外,它还包含自动配置特性,当检测到特定库的存在时,会自动配置相关的服务,例如数据源、缓存、安全等...