一. 创建内嵌的Jetty服务器主要有以下几个步骤:
(1)创建一个Server实例 (2)添加或者配置一个Connectors (3)添加或者配置 Handler and/or Contexts and/or Servlet (4)启动Server (5)等待服务,或者使用线程做一些其他的事情二. 创建一个最简单的服务器
由于该服务器没有处理程序handler,所以它将会对所有的请求返回404packageorg.eclipse.jetty.embedded;
importorg.eclipse.jetty.server.Server;
/** The simplest possible Jetty server.
*/
publicclass SimplestServer {
publicstatic void main(String[] args) throwsException {
Server server = newServer(8080);
server.start();
server.join();
}
}
三. 使用Handler
为了对一个request产生response ,Jetty需要为server添加一个Handler处理程序。一个Handler处理程序可以有以下几中行为:1. 检查或者修改HTTP request 2. 产生完整的HTTP response 3. 调用其它的Handler处理程序 4. 选择一个或多个Handlers去调用下面实例是一个简单的Handler处理程序
packageorg.eclipse.jetty.embedded;传递给handle方法的参数有以下几个:
importjava.io.IOException;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.eclipse.jetty.server.Request;
importorg.eclipse.jetty.server.handler.AbstractHandler;
publicclass HelloHandler extendsAbstractHandler {
finalString _greeting;
finalString _body;
publicHelloHandler() {
_greeting = "Hello World";
_body = null;
}
publicHelloHandler(String greeting) {
_greeting = greeting;
_body = null;
}
publicHelloHandler(String greeting, String body) {
_greeting = greeting;
_body = body;
}
publicvoid handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)throwsIOException, ServletException {
response.setContentType("text/html;charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
baseRequest.setHandled(true);
response.getWriter().println("<h1>"+ _greeting + "</h1>");
if(_body != null) response.getWriter().println(_body);
}
}
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 by a filter or servlet.
response–the response, which may have been wrapped by a filter or servlet.
四. 运行HelloWordHandler
publicstatic void main(String[] args) throwsException {
Server server = newServer(8080);
server.setHandler(newHelloHandler());
server.start();
server.join();
}
五. 资源处理程序 Resource Handler
FileServer类展示如何使用ResourceHandler来提供对静态资源的服务。packageorg.eclipse.jetty.embedded;
importorg.eclipse.jetty.server.Handler;
importorg.eclipse.jetty.server.Server;
importorg.eclipse.jetty.server.handler.DefaultHandler;
importorg.eclipse.jetty.server.handler.HandlerList;
importorg.eclipse.jetty.server.handler.ResourceHandler;
/** Simple Jetty FileServer.
* This is a simple example of Jetty configured as a FileServer.
*/
publicclass FileServer {
publicstatic void main(String[] args) throwsException {
Server server = newServer(8080);
ResourceHandler resource_handler = newResourceHandler();
resource_handler.setDirectoriesListed(true);
resource_handler.setWelcomeFiles(newString[] { "index.html"});
resource_handler.setResourceBase(".");
HandlerList handlers = newHandlerList();
handlers.setHandlers(newHandler[] { resource_handler, newDefaultHandler() });
server.setHandler(handlers);
server.start();
server.join();
}
}
对于不匹配该静态资源的请求将会返回一个404,对于不匹配静态资源的请求,有DefaultHandler实例处理,返回404
六. 内嵌的连接器 Embedding Connectors
在上面的例子中,一个Server实例被传入了一个端口号,在Server内部默认的创建了一个连接器Connector用来坚挺该端口的请求。然而,许多时候默认的连接器并不能够满足一些需要,所以需要自定义自己的Connectors. OneConnector.java 实例化,配置,并且添加了一个简单的HTTP连接器实例的Serverpackageorg.eclipse.jetty.embedded;
importorg.eclipse.jetty.server.Server;
importorg.eclipse.jetty.server.ServerConnector;
/**
* A Jetty server with one connectors.
*/
publicclass OneConnector {
publicstatic void main(String[] args) throwsException {
Server server = newServer();
ServerConnector http = newServerConnector(server);
http.setHost("localhost");
http.setPort(8080);
http.setIdleTimeout(30000);
server.addConnector(http);
server.setHandler(newHelloHandler());
server.start();
server.join();
}
}
七. 多个连接器
当配置多个Connector,比如HTTP,HTTPS,可能更希望共享一些HTTP配置参数,为了实现这个目标,需要指定为ServerConnector配置一个ConnectionFactory,并且提供一些可以共享的常用参数。 ManyConnectors.java配置了两个连接器,分别是http connector 和 https connector,该实例在本文最下方。 八,内嵌Servlet (Embedding Servlet) Servlet提供了处理http请求的标准方式,Servlet和Jetty的Handler是相似的,除了它的request对象是不能够修改的。Servlet在jetty中是通过ServletHandler处理类来处理的。它使用标准的路径映射(path mapping)来匹配Servlet请求。MinimalServlet.java 创建了一个ServletHandler实例,并且配置了一个简单的HelloServlet。packageorg.eclipse.jetty.embedded;
importjava.io.IOException;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.eclipse.jetty.server.Server;
importorg.eclipse.jetty.servlet.ServletHandler;
publicclass MinimalServlets {
publicstatic void main(String[] args) throwsException {
Server server = newServer(8080);
ServletHandler handler = newServletHandler();
server.setHandler(handler);
handler.addServletWithMapping(HelloServlet.class,"/*");
server.start();
server.join();
}
@SuppressWarnings("serial")
publicstatic class HelloServlet extendsHttpServlet {
@Override
protectedvoid doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().println("<h1>Hello SimpleServlet</h1>");
}
}
}
八. 内嵌的上下文 Embedding Contexts
ContextHandler是只对匹配所属context的URI前缀请求响应的ScopedHandler,每一个匹配上下文url的请求,都有一个对应的handler,有效的上下文(context)主要有以下几种:A Classloader that is set as the Thread context classloader while request handling is in scope.
A set of attributes that is available via the ServletContext API.
A set of init parameters that is available via the ServletContext API.
A base Resource which is used as the document root for static resource requests via the ServletContext API.
A set of virtual host names.
packageorg.eclipse.jetty.embedded;当有许多上下文时,可以使用 ContextHandlerCollection 来有效的管理 ContextHandler,下面的实例展示了这一点:
importorg.eclipse.jetty.server.Server;
importorg.eclipse.jetty.server.handler.ContextHandler;
publicclass OneContext {
publicstatic void main(String[] args) throwsException {
Server server = newServer(8080);
ContextHandler context = newContextHandler();
context.setContextPath("/");
context.setResourceBase(".");
context.setClassLoader(Thread.currentThread().getContextClassLoader());
context.setHandler(newHelloHandler());
server.setHandler(context);
server.start();
server.join();
}
}
packageorg.eclipse.jetty.embedded;
importorg.eclipse.jetty.server.Handler;
importorg.eclipse.jetty.server.Server;
importorg.eclipse.jetty.server.handler.ContextHandler;
importorg.eclipse.jetty.server.handler.ContextHandlerCollection;
publicclass ManyContexts {
publicstatic void main(String[] args) throwsException {
Server server = newServer(8080);
ContextHandler context = newContextHandler("/");
context.setContextPath("/");
context.setHandler(newHelloHandler("Root Hello"));
ContextHandler contextFR = newContextHandler("/fr");
contextFR.setHandler(newHelloHandler("Bonjoir"));
ContextHandler contextIT = newContextHandler("/it");
contextIT.setHandler(newHelloHandler("Bongiorno"));
ContextHandler contextV = newContextHandler("/");
contextV.setVirtualHosts(newString[] { "127.0.0.2"});
contextV.setHandler(newHelloHandler("Virtual Hello"));
ContextHandlerCollection contexts = newContextHandlerCollection();
contexts.setHandlers(newHandler[] { context, contextFR, contextIT, contextV });
server.setHandler(contexts);
server.start();
server.join();
}
}
九. 内嵌多个Servlet上下文 Embedding ServletContexts
ServletContextHandler是一个专门支持Session和Servlets的上下文处理程序ContextHandler,下面的实例展示了这一点,其中DefaultServlet是一个继承HttpServlet的简单Servlet.packageorg.eclipse.jetty.embedded;
importorg.eclipse.jetty.server.Server;
importorg.eclipse.jetty.servlet.ServletContextHandler;
importorg.eclipse.jetty.servlet.ServletHolder;
publicclass OneServletContext {
publicstatic void main(String[] args) throwsException {
Server server = newServer(8080);
ServletContextHandler context = newServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
server.setHandler(context);
context.addServlet(org.eclipse.jetty.servlet.DefaultServlet.class,"/");
context.addServlet(newServletHolder(newDumpServlet()), "/dump/*");
server.start();
server.join();
}
}
附录:
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created by superman on 14-1-11.
*/
public class DumpServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().println("<h1>DumpServlet</h1><pre>");
response.getWriter().println("requestURI=" + request.getRequestURI());
response.getWriter().println("contextPath=" + request.getContextPath());
response.getWriter().println("servletPath=" + request.getServletPath());
response.getWriter().println("pathInfo=" + request.getPathInfo());
response.getWriter().println("session=" + request.getSession(true).getId());
String r=request.getParameter("resource");
if (r!=null)
response.getWriter().println("resource("+r+")=" + getServletContext().getResource(r));
response.getWriter().println("</pre>");
}
}
package jetty;
import org.eclipse.jetty.server.*;
import org.eclipse.jetty.util.ssl.SslContextFactory;
/**
* Created by superman on 14-1-11.
*/
public class ManyConnectors {
public static void main(String[] args) throws Exception {
String jetty_home = System.getProperty("jetty.home", "D:\\jetty-distribution-9.1.0.v20131115");
System.setProperty("jetty.home", jetty_home);
Server server = new Server();
//configure some common parameters
HttpConfiguration httpConfig = new HttpConfiguration();
httpConfig.setSecureScheme("https");
httpConfig.setSecurePort(8443);
httpConfig.setOutputBufferSize(32768);
// HTTP connector
// The first server connector we create is the one for http, passing in the http configuration we configured
// above so it can get things like the output buffer size, etc. We also set the port (8080) and configure an
// idle timeout.
ServerConnector httpConnector = new ServerConnector(server, new HttpConnectionFactory(httpConfig));
httpConnector.setPort(8080);
httpConnector.setIdleTimeout(30000);
// SSL Context Factory for HTTPS and SPDY
// SSL requires a certificate so we configure a factory for ssl contents with information pointing to what
// keystore the ssl connection needs to know about. Much more configuration is available the ssl context,
// including things like choosing the particular certificate out of a keystore to be used.69
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setKeyStorePath(jetty_home + "/etc/keystore");
sslContextFactory.setKeyStorePassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4");
sslContextFactory.setKeyManagerPassword("OBF:1u2u1wml1z7s1z7a1wnl1u2g");
// HTTPS Configuration
// A new HttpConfiguration object is needed for the next connector and you can pass the old one as an
// argument to effectively clone the contents. On this HttpConfiguration object we add a
// SecureRequestCustomizer which is how a new connector is able to resolve the https connection before
// handing control over to the Jetty Server.
HttpConfiguration https_config = new HttpConfiguration(httpConfig);
https_config.addCustomizer(new SecureRequestCustomizer());
// HTTPS connector
// We create a second ServerConnector, passing in the http configuration we just made along with the
// previously created ssl context factory. Next we set the port and a longer idle timeout.
ServerConnector https = new ServerConnector(server,
new SslConnectionFactory(sslContextFactory, "http/1.1"),
new HttpConnectionFactory(https_config));
https.setPort(8443);
https.setIdleTimeout(500000);
server.setConnectors(new Connector[]{httpConnector, https});
server.setHandler(new HelloWorldHandler("hello", "welcome"));
server.start();
server.join();
}
}
翻译来源:http://www.eclipse.org/jetty/documentation/current/index.html