文章首发于公众号【大数据学徒】,感兴趣请搜索 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
,运行效果为:
虽然页面很是的朴实,但确实达到了预期的效果。
欢迎交流讨论,吐槽建议,分享收藏。