jetty在项目中的应用
来源:互联网 发布:淘宝天猫流量互刷软件 编辑:程序博客网 时间:2024/06/05 18:18
jetty是一个轻量级容器,你可以使用它作为生产应用服务器,不过我一般用它来做开发环境的启动容器。使用main函数就可以运行起来,使用非常方便。至于生产环境,可替代的方案较多,故而在开发环境使用jetty作为我的应用中间件。
一 maven插件jetty方式
在pom.xml中添加下面的插件,通过jetty:run -Djetty.port=8081
可启动服务
<plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>9.1.6.v20160112</version> <configuration> <scanIntervalSeconds>10</scanIntervalSeconds> <webApp> <contextPath>/webIM</contextPath> </webApp> </configuration></plugin>
二 外置jetty的方式
这种方式比较自由
1 pom.xml
在pom.xml中引入jetty相关的jar。
<jetty.version>8.1.16.v20140903</jetty.version><!-- jetty begin --> <dependency> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-webapp</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-jsp</artifactId> <scope>test</scope> </dependency> <!-- jetty end -->
2 src/test/resources
这个目录主要配置jetty相关的xml的配置
2.1 jetty.xml
<?xml version="1.0"?><!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure.dtd"><!-- =============================================================== --><!-- Configure the Jetty Server --><!-- --><!-- Documentation of this file format can be found at: --><!-- http://wiki.eclipse.org/Jetty/Reference/jetty.xml_syntax --><!-- --><!-- Additional configuration files are available in $JETTY_HOME/etc --><!-- and can be mixed in. For example: --><!-- java -jar start.jar etc/jetty-ssl.xml --><!-- --><!-- See start.ini file for the default configuraton files --><!-- =============================================================== --><Configure id="Server" class="org.eclipse.jetty.server.Server"> <!-- =========================================================== --> <!-- Server Thread Pool --> <!-- =========================================================== --> <Set name="ThreadPool"> <!-- Default queued blocking threadpool --> <New class="org.eclipse.jetty.util.thread.QueuedThreadPool"> <Set name="minThreads">10</Set> <Set name="maxThreads">200</Set> <Set name="detailedDump">false</Set> </New> </Set> <!-- =========================================================== --> <!-- Set handler Collection Structure --> <!-- =========================================================== --> <Set name="handler"> <New id="Handlers" class="org.eclipse.jetty.server.handler.HandlerCollection"> <Set name="handlers"> <Array type="org.eclipse.jetty.server.Handler"> <Item> <New id="Contexts" class="org.eclipse.jetty.server.handler.ContextHandlerCollection"/> </Item> <Item> <New id="DefaultHandler" class="org.eclipse.jetty.server.handler.DefaultHandler"/> </Item> <Item> <New class="org.mortbay.jetty.webapp.WebAppContext"> <Set name="contextPath">/hko/upload</Set> <Set name="resourceBase">E:/upload/2016-01-16</Set> <Call name="addServlet"> <Arg>org.mortbay.jetty.servlet.DefaultServlet</Arg> <Arg>/test</Arg> </Call> </New> </Item> <Item> <New id="uploadHanlder" class="org.eclipse.jetty.webapp.WebAppContext"> <Set name="contextPath">/upload</Set> <Set name="resourceBase">E:/upload</Set> </New> </Item> </Array> </Set> </New> </Set> <Call name="addBean"> <Arg> <New id="DeploymentManager" class="org.eclipse.jetty.deploy.DeploymentManager"> <Set name="contexts"> <Ref id="Contexts" /> </Set> <Call name="setContextAttribute"> <Arg>org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern</Arg> <Arg>.*/.*jsp-api-[^/]*\.jar$|.*/.*jsp-[^/]*\.jar$|.*/.*taglibs[^/]*\.jar$</Arg> </Call> <!-- Add a customize step to the deployment lifecycle --> <!-- uncomment and replace DebugBinding with your extended AppLifeCycle.Binding class--> <Call name="insertLifeCycleNode"> <Arg>deployed</Arg> <Arg>starting</Arg> <Arg>customise</Arg> </Call> <Call name="addLifeCycleBinding"> <Arg> <New class="org.eclipse.jetty.deploy.bindings.DebugBinding"> <Arg>customise</Arg> </New> </Arg> </Call> </New> </Arg> </Call> <!-- =========================================================== --> <!-- extra options --> <!-- =========================================================== --> <Set name="stopAtShutdown">true</Set> <Set name="sendServerVersion">true</Set> <Set name="sendDateHeader">true</Set> <Set name="gracefulShutdown">1000</Set> <Set name="dumpAfterStart">false</Set> <Set name="dumpBeforeStop">false</Set></Configure>
2.2 webdefault-windows.xml
<?xml version="1.0" encoding="ISO-8859-1"?><!-- ===================================================================== --><!-- This file contains the default descriptor for web applications. --><!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --><!-- The intent of this descriptor is to include jetty specific or common --><!-- configuration for all webapps. If a context has a webdefault.xml --><!-- descriptor, it is applied before the contexts own web.xml file --><!-- --><!-- A context may be assigned a default descriptor by: --><!-- + Calling WebApplicationContext.setDefaultsDescriptor --><!-- + Passed an arg to addWebApplications --><!-- --><!-- This file is used both as the resource within the jetty.jar (which is --><!-- used as the default if no explicit defaults descriptor is set) and it --><!-- is copied to the etc directory of the Jetty distro and explicitly --><!-- by the jetty.xml file. --><!-- --><!-- ===================================================================== --><web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" metadata-complete="true" version="2.5"> <description> Default web.xml file. This file is applied to a Web application before it's own WEB_INF/web.xml file </description> <!-- ==================================================================== --> <!-- Removes static references to beans from javax.el.BeanELResolver to --> <!-- ensure webapp classloader can be released on undeploy --> <!-- ==================================================================== --> <listener> <listener-class>org.eclipse.jetty.servlet.listener.ELContextCleaner</listener-class> </listener> <!-- ==================================================================== --> <!-- Removes static cache of Methods from java.beans.Introspector to --> <!-- ensure webapp classloader can be released on undeploy --> <!-- ==================================================================== --> <listener> <listener-class>org.eclipse.jetty.servlet.listener.IntrospectorCleaner</listener-class> </listener> <!-- ==================================================================== --> <!-- Context params to control Session Cookies --> <!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --> <!-- UNCOMMENT TO ACTIVATE <context-param> <param-name>org.eclipse.jetty.servlet.SessionDomain</param-name> <param-value>127.0.0.1</param-value> </context-param> <context-param> <param-name>org.eclipse.jetty.servlet.SessionPath</param-name> <param-value>/</param-value> </context-param> <context-param> <param-name>org.eclipse.jetty.servlet.MaxAge</param-name> <param-value>-1</param-value> </context-param> --> <!-- ==================================================================== --> <!-- The default servlet. --> <!-- This servlet, normally mapped to /, provides the handling for static --> <!-- content, OPTIONS and TRACE methods for the context. --> <!-- The following initParameters are supported: --> <!-- * acceptRanges If true, range requests and responses are * supported * * dirAllowed If true, directory listings are returned if no * welcome file is found. Else 403 Forbidden. * * welcomeServlets If true, attempt to dispatch to welcome files * that are servlets, but only after no matching static * resources could be found. If false, then a welcome * file must exist on disk. If "exact", then exact * servlet matches are supported without an existing file. * Default is true. * * This must be false if you want directory listings, * but have index.jsp in your welcome file list. * * redirectWelcome If true, welcome files are redirected rather than * forwarded to. * * gzip If set to true, then static content will be served as * gzip content encoded if a matching resource is * found ending with ".gz" * * resourceBase Set to replace the context resource base * * resourceCache If set, this is a context attribute name, which the servlet * will use to look for a shared ResourceCache instance. * * relativeResourceBase * Set with a pathname relative to the base of the * servlet context root. Useful for only serving static content out * of only specific subdirectories. * * aliases If True, aliases of resources are allowed (eg. symbolic * links and caps variations). May bypass security constraints. * * maxCacheSize The maximum total size of the cache or 0 for no cache. * maxCachedFileSize The maximum size of a file to cache * maxCachedFiles The maximum number of files to cache * * useFileMappedBuffer * If set to true, it will use mapped file buffer to serve static content * when using NIO connector. Setting this value to false means that * a direct buffer will be used instead of a mapped file buffer. * By default, this is set to true. * * cacheControl If set, all static content will have this value set as the cache-control * header. --> <!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --> <servlet> <servlet-name>default</servlet-name> <servlet-class>org.eclipse.jetty.servlet.DefaultServlet</servlet-class> <init-param> <param-name>aliases</param-name> <param-value>false</param-value> </init-param> <init-param> <param-name>acceptRanges</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>dirAllowed</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>welcomeServlets</param-name> <param-value>false</param-value> </init-param> <init-param> <param-name>redirectWelcome</param-name> <param-value>false</param-value> </init-param> <init-param> <param-name>maxCacheSize</param-name> <param-value>256000000</param-value> </init-param> <init-param> <param-name>maxCachedFileSize</param-name> <param-value>200000000</param-value> </init-param> <init-param> <param-name>maxCachedFiles</param-name> <param-value>2048</param-value> </init-param> <init-param> <param-name>gzip</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>useFileMappedBuffer</param-name> <param-value>false</param-value> </init-param> <!-- <init-param> <param-name>resourceCache</param-name> <param-value>resourceCache</param-value> </init-param> --> <!-- <init-param> <param-name>cacheControl</param-name> <param-value>max-age=3600,public</param-value> </init-param> --> <load-on-startup>0</load-on-startup> </servlet> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- ==================================================================== --> <!-- JSP Servlet --> <!-- This is the jasper JSP servlet from the jakarta project --> <!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --> <!-- The JSP page compiler and execution servlet, which is the mechanism --> <!-- used by Glassfish to support JSP pages. Traditionally, this servlet --> <!-- is mapped to URL patterh "*.jsp". This servlet supports the --> <!-- following initialization parameters (default values are in square --> <!-- brackets): --> <!-- --> <!-- checkInterval If development is false and reloading is true, --> <!-- background compiles are enabled. checkInterval --> <!-- is the time in seconds between checks to see --> <!-- if a JSP page needs to be recompiled. [300] --> <!-- --> <!-- compiler Which compiler Ant should use to compile JSP --> <!-- pages. See the Ant documenation for more --> <!-- information. [javac] --> <!-- --> <!-- classdebuginfo Should the class file be compiled with --> <!-- debugging information? [true] --> <!-- --> <!-- classpath What class path should I use while compiling --> <!-- generated servlets? [Created dynamically --> <!-- based on the current web application] --> <!-- Set to ? to make the container explicitly set --> <!-- this parameter. --> <!-- --> <!-- development Is Jasper used in development mode (will check --> <!-- for JSP modification on every access)? [true] --> <!-- --> <!-- enablePooling Determines whether tag handler pooling is --> <!-- enabled [true] --> <!-- --> <!-- fork Tell Ant to fork compiles of JSP pages so that --> <!-- a separate JVM is used for JSP page compiles --> <!-- from the one Tomcat is running in. [true] --> <!-- --> <!-- ieClassId The class-id value to be sent to Internet --> <!-- Explorer when using <jsp:plugin> tags. --> <!-- [clsid:8AD9C840-044E-11D1-B3E9-00805F499D93] --> <!-- --> <!-- javaEncoding Java file encoding to use for generating java --> <!-- source files. [UTF-8] --> <!-- --> <!-- keepgenerated Should we keep the generated Java source code --> <!-- for each page instead of deleting it? [true] --> <!-- --> <!-- logVerbosityLevel The level of detailed messages to be produced --> <!-- by this servlet. Increasing levels cause the --> <!-- generation of more messages. Valid values are --> <!-- FATAL, ERROR, WARNING, INFORMATION, and DEBUG. --> <!-- [WARNING] --> <!-- --> <!-- mappedfile Should we generate static content with one --> <!-- print statement per input line, to ease --> <!-- debugging? [false] --> <!-- --> <!-- --> <!-- reloading Should Jasper check for modified JSPs? [true] --> <!-- --> <!-- suppressSmap Should the generation of SMAP info for JSR45 --> <!-- debugging be suppressed? [false] --> <!-- --> <!-- dumpSmap Should the SMAP info for JSR45 debugging be --> <!-- dumped to a file? [false] --> <!-- False if suppressSmap is true --> <!-- --> <!-- scratchdir What scratch directory should we use when --> <!-- compiling JSP pages? [default work directory --> <!-- for the current web application] --> <!-- --> <!-- tagpoolMaxSize The maximum tag handler pool size [5] --> <!-- --> <!-- xpoweredBy Determines whether X-Powered-By response --> <!-- header is added by generated servlet [false] --> <!-- --> <!-- If you wish to use Jikes to compile JSP pages: --> <!-- Set the init parameter "compiler" to "jikes". Define --> <!-- the property "-Dbuild.compiler.emacs=true" when starting Jetty --> <!-- to cause Jikes to emit error messages in a format compatible with --> <!-- Jasper. --> <!-- If you get an error reporting that jikes can't use UTF-8 encoding, --> <!-- try setting the init parameter "javaEncoding" to "ISO-8859-1". --> <!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --> <servlet id="jsp"> <servlet-name>jsp</servlet-name> <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class> <init-param> <param-name>logVerbosityLevel</param-name> <param-value>DEBUG</param-value> </init-param> <init-param> <param-name>fork</param-name> <param-value>false</param-value> </init-param> <init-param> <param-name>xpoweredBy</param-name> <param-value>false</param-value> </init-param> <!-- <init-param> <param-name>classpath</param-name> <param-value>?</param-value> </init-param> --> <load-on-startup>0</load-on-startup> </servlet> <servlet-mapping> <servlet-name>jsp</servlet-name> <url-pattern>*.jsp</url-pattern> <url-pattern>*.jspf</url-pattern> <url-pattern>*.jspx</url-pattern> <url-pattern>*.xsp</url-pattern> <url-pattern>*.JSP</url-pattern> <url-pattern>*.JSPF</url-pattern> <url-pattern>*.JSPX</url-pattern> <url-pattern>*.XSP</url-pattern> </servlet-mapping> <!-- ==================================================================== --> <!-- Dynamic Servlet Invoker. --> <!-- This servlet invokes anonymous servlets that have not been defined --> <!-- in the web.xml or by other means. The first element of the pathInfo --> <!-- of a request passed to the envoker is treated as a servlet name for --> <!-- an existing servlet, or as a class name of a new servlet. --> <!-- This servlet is normally mapped to /servlet/* --> <!-- This servlet support the following initParams: --> <!-- --> <!-- nonContextServlets If false, the invoker can only load --> <!-- servlets from the contexts classloader. --> <!-- This is false by default and setting this --> <!-- to true may have security implications. --> <!-- --> <!-- verbose If true, log dynamic loads --> <!-- --> <!-- * All other parameters are copied to the --> <!-- each dynamic servlet as init parameters --> <!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --> <!-- Uncomment for dynamic invocation <servlet> <servlet-name>invoker</servlet-name> <servlet-class>org.eclipse.jetty.servlet.Invoker</servlet-class> <init-param> <param-name>verbose</param-name> <param-value>false</param-value> </init-param> <init-param> <param-name>nonContextServlets</param-name> <param-value>false</param-value> </init-param> <init-param> <param-name>dynamicParam</param-name> <param-value>anyValue</param-value> </init-param> <load-on-startup>0</load-on-startup> </servlet> <servlet-mapping> <servlet-name>invoker</servlet-name> <url-pattern>/servlet/*</url-pattern> </servlet-mapping> --> <!-- ==================================================================== --> <session-config> <session-timeout>30</session-timeout> </session-config> <!-- ==================================================================== --> <!-- Default MIME mappings --> <!-- The default MIME mappings are provided by the mime.properties --> <!-- resource in the org.eclipse.jetty.server.jar file. Additional or modified --> <!-- mappings may be specified here --> <!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --> <!-- UNCOMMENT TO ACTIVATE <mime-mapping> <extension>mysuffix</extension> <mime-type>mymime/type</mime-type> </mime-mapping> --> <!-- ==================================================================== --> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- ==================================================================== --> <locale-encoding-mapping-list> <locale-encoding-mapping> <locale>ar</locale> <encoding>ISO-8859-6</encoding> </locale-encoding-mapping> <locale-encoding-mapping> <locale>be</locale> <encoding>ISO-8859-5</encoding> </locale-encoding-mapping> <locale-encoding-mapping> <locale>bg</locale> <encoding>ISO-8859-5</encoding> </locale-encoding-mapping> <locale-encoding-mapping> <locale>ca</locale> <encoding>ISO-8859-1</encoding> </locale-encoding-mapping> <locale-encoding-mapping> <locale>cs</locale> <encoding>ISO-8859-2</encoding> </locale-encoding-mapping> <locale-encoding-mapping> <locale>da</locale> <encoding>ISO-8859-1</encoding> </locale-encoding-mapping> <locale-encoding-mapping> <locale>de</locale> <encoding>ISO-8859-1</encoding> </locale-encoding-mapping> <locale-encoding-mapping> <locale>el</locale> <encoding>ISO-8859-7</encoding> </locale-encoding-mapping> <locale-encoding-mapping> <locale>en</locale> <encoding>ISO-8859-1</encoding> </locale-encoding-mapping> <locale-encoding-mapping> <locale>es</locale> <encoding>ISO-8859-1</encoding> </locale-encoding-mapping> <locale-encoding-mapping> <locale>et</locale> <encoding>ISO-8859-1</encoding> </locale-encoding-mapping> <locale-encoding-mapping> <locale>fi</locale> <encoding>ISO-8859-1</encoding> </locale-encoding-mapping> <locale-encoding-mapping> <locale>fr</locale> <encoding>ISO-8859-1</encoding> </locale-encoding-mapping> <locale-encoding-mapping> <locale>hr</locale> <encoding>ISO-8859-2</encoding> </locale-encoding-mapping> <locale-encoding-mapping> <locale>hu</locale> <encoding>ISO-8859-2</encoding> </locale-encoding-mapping> <locale-encoding-mapping> <locale>is</locale> <encoding>ISO-8859-1</encoding> </locale-encoding-mapping> <locale-encoding-mapping> <locale>it</locale> <encoding>ISO-8859-1</encoding> </locale-encoding-mapping> <locale-encoding-mapping> <locale>iw</locale> <encoding>ISO-8859-8</encoding> </locale-encoding-mapping> <locale-encoding-mapping> <locale>ja</locale> <encoding>Shift_JIS</encoding> </locale-encoding-mapping> <locale-encoding-mapping> <locale>ko</locale> <encoding>EUC-KR</encoding> </locale-encoding-mapping> <locale-encoding-mapping> <locale>lt</locale> <encoding>ISO-8859-2</encoding> </locale-encoding-mapping> <locale-encoding-mapping> <locale>lv</locale> <encoding>ISO-8859-2</encoding> </locale-encoding-mapping> <locale-encoding-mapping> <locale>mk</locale> <encoding>ISO-8859-5</encoding> </locale-encoding-mapping> <locale-encoding-mapping> <locale>nl</locale> <encoding>ISO-8859-1</encoding> </locale-encoding-mapping> <locale-encoding-mapping> <locale>no</locale> <encoding>ISO-8859-1</encoding> </locale-encoding-mapping> <locale-encoding-mapping> <locale>pl</locale> <encoding>ISO-8859-2</encoding> </locale-encoding-mapping> <locale-encoding-mapping> <locale>pt</locale> <encoding>ISO-8859-1</encoding> </locale-encoding-mapping> <locale-encoding-mapping> <locale>ro</locale> <encoding>ISO-8859-2</encoding> </locale-encoding-mapping> <locale-encoding-mapping> <locale>ru</locale> <encoding>ISO-8859-5</encoding> </locale-encoding-mapping> <locale-encoding-mapping> <locale>sh</locale> <encoding>ISO-8859-5</encoding> </locale-encoding-mapping> <locale-encoding-mapping> <locale>sk</locale> <encoding>ISO-8859-2</encoding> </locale-encoding-mapping> <locale-encoding-mapping> <locale>sl</locale> <encoding>ISO-8859-2</encoding> </locale-encoding-mapping> <locale-encoding-mapping> <locale>sq</locale> <encoding>ISO-8859-2</encoding> </locale-encoding-mapping> <locale-encoding-mapping> <locale>sr</locale> <encoding>ISO-8859-5</encoding> </locale-encoding-mapping> <locale-encoding-mapping> <locale>sv</locale> <encoding>ISO-8859-1</encoding> </locale-encoding-mapping> <locale-encoding-mapping> <locale>tr</locale> <encoding>ISO-8859-9</encoding> </locale-encoding-mapping> <locale-encoding-mapping> <locale>uk</locale> <encoding>ISO-8859-5</encoding> </locale-encoding-mapping> <locale-encoding-mapping> <locale>zh</locale> <encoding>GB2312</encoding> </locale-encoding-mapping> <locale-encoding-mapping> <locale>zh_TW</locale> <encoding>Big5</encoding> </locale-encoding-mapping> </locale-encoding-mapping-list> <security-constraint> <web-resource-collection> <web-resource-name>Disable TRACE</web-resource-name> <url-pattern>/</url-pattern> <http-method>TRACE</http-method> </web-resource-collection> <auth-constraint /> </security-constraint></web-app>
3 src/test/java
3.1 JettyFactory.java
主要jetty开发环境的虚拟目录通过uploadContext.setContextPath和uploadContext.setResourceBase来实现,注意下方代码
import java.util.List;import org.apache.commons.lang3.StringUtils;import org.eclipse.jetty.server.Connector;import org.eclipse.jetty.server.Handler;import org.eclipse.jetty.server.Server;import org.eclipse.jetty.server.handler.ContextHandlerCollection;import org.eclipse.jetty.server.nio.SelectChannelConnector;import org.eclipse.jetty.webapp.WebAppClassLoader;import org.eclipse.jetty.webapp.WebAppContext;import com.google.common.collect.Lists;/** * 创建Jetty Server的工厂类. * * @author calvin */public class JettyFactory { private static final String DEFAULT_WEBAPP_PATH = "src/main/webapp"; private static final String WINDOWS_WEBDEFAULT_PATH = "src/test/resources/jetty/webdefault-windows.xml"; /** * 创建用于开发运行调试的Jetty Server, 以src/main/webapp为Web应用目录. */ public static Server createServerInSource(int port, String contextPath) { Server server = new Server(); // 设置在JVM退出时关闭Jetty的钩子。 server.setStopAtShutdown(true); SelectChannelConnector connector = new SelectChannelConnector(); connector.setPort(port); // 解决Windows下重复启动Jetty居然不报告端口冲突的问题. connector.setReuseAddress(false); server.setConnectors(new Connector[] { connector }); // 上下文 ContextHandlerCollection contextHandlerCollection = new ContextHandlerCollection(); // 当前应用 WebAppContext webContext = new WebAppContext(DEFAULT_WEBAPP_PATH, contextPath); // 修改webdefault.xml,解决Windows下Jetty Lock住静态文件的问题. webContext.setDefaultsDescriptor(WINDOWS_WEBDEFAULT_PATH); contextHandlerCollection.addHandler(webContext); // 虚拟目录 WebAppContext uploadContext = new WebAppContext(); uploadContext.setContextPath("/abs/upload"); uploadContext.setResourceBase("E:/upload"); contextHandlerCollection.addHandler(uploadContext); // server.setHandler(contextHandlerCollection); return server; } private static WebAppContext getWebAppContext(Server server){ ContextHandlerCollection contextHandlerCollection = (ContextHandlerCollection) server.getHandler(); Handler[] handlers = contextHandlerCollection.getHandlers(); WebAppContext context = null; if (handlers!=null && handlers.length>0){ for (Handler handler:handlers){ if (((WebAppContext)handler).getContextPath().equals(QuickStartServer.CONTEXT)){ context = (WebAppContext)handler; } } } return context; } /** * 设置除jstl-*.jar外其他含tld文件的jar包的名称. * jar名称不需要版本号,如sitemesh, shiro-web */ public static void setTldJarNames(Server server, String... jarNames) { WebAppContext context = getWebAppContext(server); List<String> jarNameExprssions = Lists.newArrayList(".*/jstl-[^/]*\\.jar$", ".*/.*taglibs[^/]*\\.jar$"); for (String jarName : jarNames) { jarNameExprssions.add(".*/" + jarName + "-[^/]*\\.jar$"); } context.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", StringUtils.join(jarNameExprssions, '|')); } /** * 快速重新启动application,重载target/classes与target/test-classes. */ public static void reloadContext(Server server) throws Exception { WebAppContext context = getWebAppContext(server); System.out.println("[INFO] Application reloading"); context.stop(); WebAppClassLoader classLoader = new WebAppClassLoader(context); classLoader.addClassPath("target/classes"); classLoader.addClassPath("target/test-classes"); context.setClassLoader(classLoader); context.start(); System.out.println("[INFO] Application reloaded"); }}
3.2 Profiles.java
/** * Spring profile 常用方法与profile名称。 * * @author calvin */public class Profiles { public static final String ACTIVE_PROFILE = "spring.profiles.active"; public static final String DEFAULT_PROFILE = "spring.profiles.default"; public static final String PRODUCTION = "production"; public static final String DEVELOPMENT = "development"; public static final String UNIT_TEST = "test"; public static final String FUNCTIONAL_TEST = "functional"; /** * 在Spring启动前,设置profile的环境变量。 */ public static void setProfileAsSystemProperty(String profile) { System.setProperty(ACTIVE_PROFILE, profile); }}
3.3 QuickStartServer.java
运行main函数即可启动服务。
import org.eclipse.jetty.server.Server;/** * 使用Jetty运行调试Web应用, 在Console输入回车快速重新加载应用. * * @author calvin */public class QuickStartServer { public static final int PORT = 8097; public static final String CONTEXT = "/abs"; public static final String[] TLD_JAR_NAMES = new String[] {"spring-webmvc", "shiro-web"}; public static void main(String[] args) throws Exception { // 设定Spring的profile Profiles.setProfileAsSystemProperty(Profiles.DEVELOPMENT); // 启动Jetty Server server = JettyFactory.createServerInSource(PORT, CONTEXT); JettyFactory.setTldJarNames(server, TLD_JAR_NAMES); try { server.start(); System.out.println("[INFO] 服务启动 http://localhost:" + PORT + CONTEXT); System.out.println("[HINT] 按回车迅速重启"); // 等待用户输入回车重载应用. while (true) { char c = (char) System.in.read(); if (c == '\n') { JettyFactory.reloadContext(server); } } } catch (Exception e) { e.printStackTrace(); System.exit(-1); } }}
三 linux中的方式
jetty官方下载地址,我下载的是9.2.21.v20170120
针对jdk1.7的版本
# 安装比较简单cd /applicationunzip jetty-distribution-9.2.21.v20170120.zipln -s jetty-distribution-9.2.21.v20170120 jetty# 配置jetty环境变量,注意要source /etc/profile,使之生效JETTY_HOME=/application/jettyexport JETTY_HOMEexport PATH=$PATH:$JETTY_HOME/bin# jetty的启动与关闭,jetty的端口默认为8080jetty.sh startjetty.sh stop
您可参考Jetty应用服务器的安装详解,见其他jetty描述,我这里只写我自己感受的东西。
Jetty实战之 安装 运行 部署,这篇文章针对jetty8.x版本做了说明,但是jetty9.x版本中配置文件有很大变化,对新版本已无太多参考价值。
tomcat中webapps中的war会被解压,但是我看jetty上却没有。原来jetty部署项目是不需要关掉服务,直接部署就可以。jetty可以通过start.ini
中jetty.port
属性来更改服务的端口。
如果jetty不解压war,那么jetty如何实现增量部署的呢。
- jetty在项目中的应用
- CMMI5在项目中的应用
- css 在项目中的应用
- ZedGraph在项目中的应用
- WMB在项目中的应用
- 缓存在项目中的应用
- Memcached在项目中的应用
- Memcached在项目中的应用
- Memcached在项目中的应用
- Log4j在项目中的应用
- Memcached在项目中的应用
- Memcached在项目中的应用
- 缓存在项目中的应用
- JBPM在项目中的应用
- 代码在项目中的应用
- Memcached在项目中的应用
- LogBack在项目中的应用
- Log4j 在项目中的应用
- 【C#MVC4】菜单管理和访问权限分配(二)
- 欢迎使用CSDN-markdown编辑器
- jQuery工具方法
- Spring MVC Post请求返回403错误,Get请求却正常?
- C#委托使用详解(Delegates)
- jetty在项目中的应用
- 洗牌算法shuffle
- Activity 生命周期详细解释
- java中参数传递
- NYOJ 114 某种序列
- JQuery二维码插件(前台生成)
- Java(线程的终止)
- PAT 1010. Radix (25)(进制转化)(暂无)
- java初级之28static关键字