设为首页 收藏本站
查看: 673|回复: 0

[经验分享] Jetty嵌入项目式开发(把jetty发布到你的应用中)

[复制链接]

尚未签到

发表于 2017-2-27 06:02:52 | 显示全部楼层 |阅读模式
Jetty/Tutorial/Embedding Jetty
这是来自Jetty官方的教程:(PS:我只是打酱油的)
使用以下示例,需要下载好 Jetty(独立版),(之前跑去下载eclpse版的结果不会用)
::::我用的是Jetty 7,跟Jetty 6相比,的确是因为多有点杂.
建议在使用以下实例的时候,将所下载的包(在jetty根目录的lib文件夹下)全部导入,有兴趣的可以一个一个导入试试,也可以根据错误,去查找哪个包有对应的类。Jetty7的分包已经很专业了,不怕看不懂


=============================================================================
阅读注意:代码中的"jetty_home"为jetty在你电脑中的根目录,不要一味的复制,黏贴。
注意修改..
=============================================================================


Introduction
将Jetty发布到你的应用中,而不是把你的应用发布到Jetty应用服务器.
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
嵌入式Jetty所需要做的事情
To embed a Jetty server, the following steps are typical:
   1. Create the server
   2. Add/Configure Connectors
   3. Add/Configure Handlers
   4. Add/Configure Servlets/Webapps to Handlers
   5. Start the server
   6. 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
{
private String greeting="Hello World";
public HelloServlet(){}
public HelloServlet(String greeting)
{
this.greeting=greeting;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().println("<h1>"+greeting+"</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 variation 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();
}
}

If during development, your application has not been assembled into a war file, then it can be run from its source components with something like:

public class OneWebAppUnassembled
{
public static void main(String[] args) throws Exception
{
Server server = new Server(8080);
WebAppContext context = new WebAppContext();
context.setDescriptor(webapp+"/WEB-INF/web.xml");
context.setResourceBase("../test-jetty-webapp/src/main/webapp");
context.setContextPath("/");
context.setParentLoaderPriority(true);
server.setHandler(context);
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();
}
}

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-347551-1-1.html 上篇帖子: eclipse集成maven+jetty关于使用jetty:run 出现本地依赖包找不到问题。 下篇帖子: Jetty 服务器架构分析(上)【转】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表