簡介
Jetty可以作為服務(wù)器像Tomcat一樣,運行web項目,作為Servlet的容器。也可以在項目中單獨引用Jetty的Jar包,通過Java代碼來對web項目進(jìn)行啟動。這樣做的目的主要是對多個web項目進(jìn)行統(tǒng)一的部署啟動。
這里主要使用的方法是第二種,即在一個Java項目中托管web項目,第一種方式未進(jìn)行過測試。
Maven 依賴
我試過手動引用jar包,但是都不太好用,最后還是通過這個Maven依賴解決的,可能這個依賴有很多重復(fù)的,但至少比網(wǎng)上的那些好用。
經(jīng)過后來的測試,將這些依賴文件的Jar包放到本地,依舊好用。
補(bǔ)充一下項目中pom.xml的創(chuàng)建方式,我使用的方法是通過idea直接創(chuàng)建的Maven項目。
一下是項目的Maven配置:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>xxx</groupId>
<artifactId>xxx</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<!-- Jetty -->
<dependency>
<groupId>org.eclipse.jetty.aggregate</groupId>
<artifactId>jetty-all</artifactId>
<version>8.0.4.v20111024</version>
</dependency>
<!-- Jetty Webapp -->
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-webapp</artifactId>
<version>8.0.4.v20111024</version>
</dependency>
<!-- JSP Support -->
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.servlet.jsp</artifactId>
<version>2.2.3</version>
</dependency>
<!-- EL Support -->
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.3</version>
</dependency>
<!-- JSTL Support -->
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.servlet.jsp.jstl</artifactId>
<version>1.2.1</version>
<exclusions>
<exclusion>
<artifactId>jstl-api</artifactId>
<groupId>javax.servlet.jsp.jstl</groupId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
</project>
Demo 示例
此 Demo 啟動的是war包,上下文路徑指的是項目啟動后的上下文地址。例如 http://ip:port/path
/**
* 啟動war包 Demo
*
* @param war war包路徑
* @param path 上下文路徑
* @param port 端口號
*/
public void startApplication(String war, String path, Integer port) {
Server server = new Server(port);
WebAppContext context = new WebAppContext();
context.setContextPath(path);
context.setWar(war);
server.setHandler(context);
try {
server.start();
} catch (Exception e) {
e.printStackTrace();
}
}
注意的問題
war包的路徑可以使用絕對路徑和相對路徑兩種,建議使用相對路徑,但是使用相對路徑讀取war包的時候在項目打包的時候會出現(xiàn)一些問題,這些問題在項目讀取諸如.xml、.properties等配置文件的時候也會出現(xiàn)問題,主要原因是打包的時候如果將這些文件打到一起,就會缺少上級目錄,如果單獨打包代碼,需要將配置文件單獨放出去,后續(xù)會詳細(xì)介紹。