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

[经验分享] jetty快速入门与嵌入使用 jetty

[复制链接]

尚未签到

发表于 2017-2-27 11:24:51 | 显示全部楼层 |阅读模式
  看到开源项目发布的时候都带一个 jsp 容器(jetty)。拿来做 demo、开发、调试的服务器还是很不错的。今天就小试下,主要把它运行起来。
  第一步下载:http://dist.codehaus.org/jetty/jetty-6.1.14/jetty-6.1.14.zip 是目前最新的稳定版。解压到如E:\jetty-6.1.14,其中比较重要的目录是:etc、contexts、webapps。个人认为可以类比tomcat的conf、conf\Catalina\localhost、webapps目录。contexts是热部署用的。
  试运行下,可以把一个简单的web项目到到webapps目录下,或是*.war,如:web-demo(或web-demo.war)放到webapps目录下。

E:\jetty-6.1.14>java -jar start.jar
2009-01-13 15:34:38.937::INFO: Logging to STDERR via org.mortbay.log.StdErrLog
2009-01-13 15:34:39.265::INFO: jetty-6.1.14
2009-01-13 15:34:39.421::INFO: Deploy E:\jetty-6.1.14\contexts\javadoc.xml -> org.mortbay.jetty.handler.ContextHandler@15cda3f{/javadoc,file:/E:/jetty-6.1.14/javadoc/}
...
2009-01-13 15:35:01.828::INFO: Opened E:\jetty-6.1.14\logs\2009_01_13.request.log
2009-01-13 15:35:01.953::INFO: Started SelectChannelConnector@127.0.0.1:8080

  打开:http://localhost:8080/web-demo ,恩有结果了。
  如果不把web-demo放到webapps目录下也可,在contexts目录下建立一个文件告诉jetty就行了。可以在contexts目录下复制test.xml为web-demo.xml,然后修改如下:


  • <?xml version="1.0" encoding="ISO-8859-1"?>  
  • <!DOCTYPE Configure PUBLIC "-//Mort Bay Consulting//DTD Configure//EN" "http://jetty.mortbay.org/configure.dtd">  
  •   
  • <Configure class="org.mortbay.jetty.webapp.WebAppContext">  
  •   
  •     <!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -->  
  •     <!-- Required minimal context configuration : -->  
  •     <!-- + contextPath -->  
  •     <!-- + war OR resourceBase -->  
  •     <!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -->  
  •     <Set name="contextPath">/web-demo</Set>  
  •     <Set name="war">e:/workspace/web-demo/WebContent</Set>  
  •   
  •     <!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -->  
  •     <!-- Optional context configuration -->  
  •     <!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -->  
  •     <Set name="extractWAR">false</Set>  
  •     <Set name="copyWebDir">false</Set>  
  •     <Set name="defaultsDescriptor">  
  •         <SystemProperty name="jetty.home" default="." />/etc/webdefault.xml</Set>  
  •     <!--  
  •         <Set name="overrideDescriptor"><SystemProperty name="jetty.home"  
  •         default="."/>/contexts/test.d/override-web.xml</Set>  
  •     -->  
  • </Configure>  
  war可以设置成绝对路径。然后再重启jetty试试看。好了, 对jetty的初步认识到这里。
  下面再来看下,怎么把它放到项目中。现我有一示例项目 e:/workspace/web-demo(称为project_home),里面的Web根目录是WebContent。
  在project_home建一个jetty目录,子目录如:contexts、etc、lib。
  把${jetty_home}/etc目录下的jetty.xml、webdefault.xml文件复制到${project_home}/jetty/etc目录中。
  把${jetty_home}/lib/jsp-2.1目录复制到${project_home}/jetty/lib目录下(如果不复制jsp-2.1或jsp-2.0也可以正常启动,只是不能解析jsp,打开主页时提示 JSP not support)。
  同样把jetty-6.1.14.jar、jetty-util-6.1.14.jar、servlet-api-2.5-6.1.14.jar复制到${project_home}/jetty/lib目录下。
  把${jetty_home}/start.jar复制到${project_home}/jetty目录下。
  接下来在${project_home}/jetty/contexts目录下加一个文件。可以是上面给出的web-demo.xml。不过war 可以改为


  • <Set name="war"><SystemProperty name="jetty.home" default="."/>/../WebContent</Set>  
  注释${project_home}/jetty/etc/jetty.xml文件中的:


  • <!--  
  • <Item>  
  •     <New id="RequestLog" class="org.mortbay.jetty.handler.RequestLogHandler" />  
  • </Item>  
  • -->  
  • <!--  
  • <Call name="addLifeCycle">  
  •     <Arg>  
  •         <New class="org.mortbay.jetty.deployer.WebAppDeployer">  
  •             <Set name="contexts"><Ref id="Contexts" /></Set>  
  •             <Set name="webAppDir"><SystemProperty name="jetty.home" default="." />/webapps</Set>  
  •             <Set name="parentLoaderPriority">false</Set>  
  •             <Set name="extract">true</Set>  
  •             <Set name="allowDuplicates">false</Set>  
  •             <Set name="defaultsDescriptor"><SystemProperty name="jetty.home" default="." />/etc/webdefault.xml</Set>  
  •         </New>  
  •     </Arg>  
  • </Call>  
  • -->  
  • <!--  
  • <Item>  
  •     <New class="org.mortbay.jetty.security.HashUserRealm">  
  •         <Set name="name">Test Realm</Set>  
  •         <Set name="config"><SystemProperty name="jetty.home" default="." />/etc/realm.properties</Set>  
  •         <Set name="refreshInterval">0</Set>  
  •     </New>  
  • </Item>  
  • -->  
  • <!--  
  • <Ref id="RequestLog">  
  •     <Set name="requestLog">  
  •         <New id="RequestLogImpl" class="org.mortbay.jetty.NCSARequestLog">  
  •             <Set name="filename"><SystemProperty name="jetty.logs" default="./logs" />/yyyy_mm_dd.request.log</Set>  
  •             <Set name="filenameDateFormat">yyyy_MM_dd</Set>  
  •             <Set name="retainDays">90</Set>  
  •             <Set name="append">true</Set>  
  •             <Set name="extended">false</Set>  
  •             <Set name="logCookies">false</Set>  
  •             <Set name="LogTimeZone">GMT</Set>  
  •         </New>  
  •     </Set>  
  • </Ref>  
  • -->  
  RequestLog 是访问记录,不注释也可,前提就是有logs目录。
  addLifeCycle 不注释也行,前提是有webapps目录。
  Test Realm 不注释也是,前提是etc目录下有realm.properties。
  配置好了,现在到E:\workspace\web-demo\jetty,运行java -jar start.jar 可以启动这个项目了。

内嵌 jetty http/servlet 代码嵌入 jetty
  N年前写了一篇关于 jetty 的使用,主要是在项目套一个简单的 jetty,但从本质上讲不是嵌入使用 jetty。平常工作中用得到现在再记录一下。纠正我标题上没写得准确。
  现在我以 maven 项目来示例。
  1、加入依赖


  •   <dependencies>  
  • <dependency>  
  •     <groupId>org.eclipse.jetty</groupId>  
  •     <artifactId>jetty-webapp</artifactId>  
  •     <version>7.6.3.v20120416</version>  
  • </dependency>  
  •   
  • <!-- support jsp -->  
  • <dependency>  
  •     <groupId>org.eclipse.jetty</groupId>  
  •     <artifactId>jetty-jsp-2.1</artifactId>  
  •     <version>7.5.4.v20111024</version>  
  • </dependency>  
  • <dependency>  
  •     <groupId>org.mortbay.jetty</groupId>  
  •     <artifactId>jsp-2.1-glassfish</artifactId>  
  •     <version>2.1.v20100127</version>  
  • </dependency>  
  • <!-- end jsp -->  
  •   
  • <dependency>  
  •     <groupId>org.slf4j</groupId>  
  •     <artifactId>slf4j-log4j12</artifactId>  
  •     <version>1.6.1</version>  
  • </dependency>  
  • <dependency>  
  •     <groupId>log4j</groupId>  
  •     <artifactId>log4j</artifactId>  
  •     <version>1.2.16</version>  
  • </dependency>  
  • <dependency>  
  •     <groupId>org.springframework</groupId>  
  •     <artifactId>spring</artifactId>  
  •     <version>2.5.6</version>  
  • </dependency>  
  •   </dependencies>  
  support jsp 的依赖不加也可以使用 servlet 和 filter。
  2、Jetty Embed Server 核心类。
Server (服务器)、SelectChannelConnector(连接器)、ServletContextHandler(web app)、FilterHolder(句柄)、ServletHolder(句柄)
  Server 加入 连接器、ServletContextHandler。
  ServletContextHandler 加入 Filter 和 Servlet 句柄。
  支持 jsp 的可以使用 WebAppContext 代替 ServletContextHandler
  核心代码
  连接池


  • //连接池  
  • SelectChannelConnector connector = new SelectChannelConnector();  
  • connector.setPort(port);  
  •        connector.setMaxIdleTime(30000);  
  •        connector.setRequestHeaderSize(8192);  
  •        QueuedThreadPool threadPool =  new QueuedThreadPool(threadNum);  
  •        threadPool.setName("embed-jetty-http");  
  •        connector.setThreadPool(threadPool);  
  •   
  • server.setConnectors(new Connector[] { connector });  
  ServletContextHandler 或 WebAppContext


  • ServletContextHandler context = null;  
  •   
  • if(webPath != null) {//webapp 可以支持 jsp  
  •     logger.info("load webPath={}", webPath);  
  •     final URL warUrl = new File(webPath).toURI().toURL();  
  •     final String warUrlString = warUrl.toExternalForm();  
  •     context = new WebAppContext(warUrlString, contextPath);  
  •     server.setHandler(context);  
  • } else {  
  •     context = new ServletContextHandler(server, contextPath);  
  • }  
  加入 servlet 或 filter


  • //add filter  
  • if(filters != null) {  
  •     for(Map.Entry<String, Filter> eFilter : filters.entrySet()) {  
  •         logger.info("add filter={}, path={}", eFilter.getValue().getClass(), eFilter.getKey());  
  •         context.addFilter(new FilterHolder(eFilter.getValue()), eFilter.getKey(), FilterMapping.DEFAULT);  
  •     }  
  • }  
  •   
  • //add servlet  
  • if(servlets != null) {  
  •     for(Map.Entry<String, Servlet> eServlet : servlets.entrySet()) {  
  •         logger.info("add servlet={}, path={}", eServlet.getValue().getClass(), eServlet.getKey());  
  •         context.addServlet(new ServletHolder(eServlet.getValue()), eServlet.getKey());  
  •     }  
  • }  
  •   
  • if(webPath == null) {  
  •     context.addServlet(DefaultServlet.class, "/*");  
  • }  
  注意:在我试用过程中发现不支持 jsp 的要加入一个 DefaultServlet。
  最后调用 server.start();
  3、示例 filter,写请求日志


  • @Override  
  • public void doFilter(ServletRequest request, ServletResponse response,  
  •         FilterChain chain) throws IOException, ServletException {  
  •   
  •     HttpServletRequest req = (HttpServletRequest) request;  
  •   
  •     logger.info("ip={}, prot={}, contextPath={}, servletPath={}, pathInfo={}, params={}", new Object[] {  
  •             req.getLocalAddr(), req.getLocalPort(), req.getContextPath(),  
  •             req.getServletPath(), req.getPathInfo(), req.getParameterMap()  
  •     });  
  •   
  •     chain.doFilter(request, response);  
  • }  
  4、示例 hello Servlet


  • @Override  
  • protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
  •         throws ServletException, IOException {  
  •   
  •     resp.setContentType("Content-Type: text/plain;charset=utf-8");  
  •     ServletOutputStream out = resp.getOutputStream();  
  •     out.println("hello embed servlet!");  
  •   
  •     Enumeration<String> name = req.getParameterNames();  
  •     while(name.hasMoreElements()) {  
  •         String myName = name.nextElement();  
  •         out.println(myName+"="+req.getParameter(myName));  
  •     }  
  • }  
  5、url 调用


  • 运行 com.chenlb.demo.jetty.JettyEmbedServer  
  •   
  • #验证 hello servlet  
  • http://localhost:8983/embed/hello?what=this-is-jetty-embed-http  
  •   
  • #验证 jsp  
  • http://localhost:8983/embed/index.jsp  
  •   
  • #管制台可以看到日志如  
  • 20:33:49.328 INFO servlet.LogFilter(36) ip=127.0.0.1, prot=8983, contextPath=/embed, servletPath=/index.jsp, pathInfo=null, params={}  
  • 20:34:02.291 INFO servlet.LogFilter(36) ip=127.0.0.1, prot=8983, contextPath=/embed, servletPath=/hello, pathInfo=/chenlb, params={what=[this-is-jetty-embed-http]}  
  jetty-embed-demo 示例代码下载 https://github.com/chenlb/demo/tree/master/jetty-embed-demo
  希望可以达到使用 嵌入 jetty 的期望。

运维网声明 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-347918-1-1.html 上篇帖子: jetty配置jndi数据源 下篇帖子: jetty启动源码分析
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

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

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

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

扫描微信二维码查看详情

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


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


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


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



合作伙伴: 青云cloud

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