今天把jetty稍微研究了一下,之前使用的全是tomcat,所以开始接触jetty感觉有点别扭,不过总算走了一遍,总结了三种启动jetty的方式,
1,直接硬编码方式,很简单:
public static void main(String[] args) {
try {
// 服务器的监听端口
Server server = new Server(8080);
// 关联一个已经存在的上下文
WebAppContext context = new WebAppContext();
// 设置描述,作为hander加载使用
context.setDescriptor("./web/WEB-INF/web.xml");
// 设置Web内容上下文路径
context.setResourceBase("./webapp");
// 设置上下文路径既访问路径的根路径
context.setContextPath("/cheng");
server.setHandler(context);
// 启动
server.start();
server.join();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
这里需要说明的是你也可以将controller(处理用户请求的servlet)作为一个对象直接在上面传给hander,不过不建议这么做。因为通过web.xml可以不影响我们正常的web开发流程,降低jetty与我们项目的耦合度。其他设置可以根据需要添加。
2,通过加载jetty.xml和webdefault.xml配置文件实现,
public static void main(String[] args) {
try {
XmlConfiguration config = new XmlConfiguration(new FileInputStream("./jetty/jetty.xml"));
Server server=(Server)config.configure();
ContextHandlerCollection handler = new ContextHandlerCollection();
WebAppContext webContext = new WebAppContext();
webContext.setContextPath("/cheng");
webContext.setDefaultsDescriptor("./jetty/webdefault.xml");
webContext.setResourceBase("src/main/webapp");
webContext.setDescriptor("src/main/webapp/WEB-INF/web.xml");
webContext.setClassLoader(Thread.currentThread().getContextClassLoader());
handler.addHandler(webContext);
server.setHandler(handler);
server.stop();
server.start();
server.join();
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
这种方式,可以将关键信息从配置文件读取。个人觉得好点。
3,通过maven插件实现,所有jetty的配置也是在插件中配,
<plugins>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.2.6.v20141205</version>
<configuration>
<webApp>
<contextPath>/cheng</contextPath>
<descriptor>src/main/webapp/WEB-INF/web.xml</descriptor>
<defaultsDescriptor>./jetty/webdefault.xml</defaultsDescriptor>
</webApp>
<stopKey>exit</stopKey>
<stopPort>9090</stopPort>
<webAppSourceDirectory>src/main/webapp</webAppSourceDirectory>
<scanIntervalSeconds>1</scanIntervalSeconds>
<!-- <connectors> <connector implementation="org.eclipse.jetty.server.nio.SelectChannelConnector">
<port>8080</port> <maxIdleTime>60000</maxIdleTime> </connector> </connectors> -->
<httpConnector>
<port>8080</port>
</httpConnector>
<requestLog implementation="org.eclipse.jetty.server.NCSARequestLog">
<filename>target/access.log</filename>
<retainDays>90</retainDays>
<append>false</append>
<extended>false</extended>
<logTimeZone>GMT+8:00</logTimeZone>
</requestLog>
<!-- <systemProperties> <systemProperty> <name>productionMode</name>
<value>${productionMode}</value> </systemProperty> </systemProperties> -->
</configuration>
</plugin>
</plugins>
上面三种本人试过,都可以通过,如有需要请根据自身需要做调整,再有就是上面jetty.xml9.0之前和之后的dtd配置是有区别的。