文章首發於公衆號【大數據學徒】,感興趣請搜索 dashujuxuetu 或者文末掃碼關注。php
如題所述,本文介紹如何經過 Jetty 的 WebAppContext 類來提供 html 等靜態資源。css
內容提要:html
代碼已上傳至 github: github.com/iamabug/sun…java
JDK版本:1.8git
Jetty 版本:9.4.24.v20191120github
開發環境:IntelliJ IDEA + Maven 插件web
新建項目 sunny
,pom.xml
文件內容爲:apache
<?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>iamabug</groupId>
<artifactId>sunny</artifactId>
<packaging>pom</packaging>
<version>0.0.1</version>
<properties>
<java.version>1.8</java.version>
<jetty.version>9.4.24.v20191120</jetty.version>
</properties>
<modules>
<module>sunny-web</module>
<module>sunny-server</module>
</modules>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
複製代碼
能夠看到,項目包含兩個子模塊:sunny-web
和 sunny-server
,前者是靜態資源模塊,後者是 Jetty 服務模塊,前者將只包含 html
, css
, js
等類型文件,後者則包含了啓動 Jetty 和配置 WebAppContext 的 Java 代碼。瀏覽器
sunny-web
目錄結構以下:bash
sunny-web $ tree
.
├── pom.xml
├── src
│ ├── main
│ │ ├── resources
│ │ └── webapp
│ │ ├── WEB-INF
│ │ │ └── web.xml
│ │ ├── images
│ │ └── index.html
│ └── test
│ └── java
└── sunny-web.iml
複製代碼
其中 web.xml
的內容爲:
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
複製代碼
其實在本文這種狀況, web.xml
能夠不存在或爲空。
index.html
的內容爲:
<!DOCTYPE html>
<html>
<head>
<title>Sunny Project</title>
</head>
<body>
<h1>Sunny Project</h1>
Get started on 2019-11-27.
</body>
</html>
複製代碼
沒有什麼信息量的 html。
sunny-server
模塊目錄結構以下:
sunny-server $ tree
.
├── pom.xml
├── src
│ ├── main
│ │ ├── java
│ │ │ └── iamabug
│ │ │ └── ServerMain.java
│ │ └── resources
│ └── test
│ └── java
└── sunny-server.iml
複製代碼
ServerMain.java
的內容爲:
package iamabug;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
public class ServerMain {
public static void main(String[] args) throws Exception {
// 建立 Server 對象
Server server = new Server(12345);
// 建立 WebAppContext 對象
WebAppContext context = new WebAppContext("./sunny-web/src/main/webapp", "/");
// 綁定
server.setHandler(context);
// 啓動
server.start();
server.join();
}
}
複製代碼
代碼邏輯很是清晰,首先建立一個 Server
對象,而後建立一個 WebAppContext
對象,這個對象接收發往 /
的請求,webapp 目錄爲 sunny-web
模塊下的 webapp
目錄,將以上兩個對象綁定,而後啓動 Server
,結束。
啓動 ServerMain
主函數,在瀏覽器訪問 http://localhost:12345
,運行效果爲:
雖然頁面很是的樸實,但確實達到了預期的效果。
歡迎交流討論,吐槽建議,分享收藏。