簡介
Jetty可以作為服務器像Tomcat一樣藕畔,運行web項目马僻,作為Servlet的容器。也可以在項目中單獨引用Jetty的Jar包注服,通過Java代碼來對web項目進行啟動韭邓。這樣做的目的主要是對多個web項目進行統(tǒng)一的部署啟動措近。
這里主要使用的方法是第二種,即在一個Java項目中托管web項目女淑,第一種方式未進行過測試瞭郑。
Maven 依賴
我試過手動引用jar包,但是都不太好用鸭你,最后還是通過這個Maven依賴解決的屈张,可能這個依賴有很多重復的,但至少比網(wǎng)上的那些好用袱巨。
經(jīng)過后來的測試阁谆,將這些依賴文件的Jar包放到本地,依舊好用愉老。
補充一下項目中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ù)會詳細介紹。