Undertow 是基於java nio的web服務器,應用比較廣泛,內置提供的PathResourceManager,可以用來直接訪問文件系統;如果你有文件需要對外提供訪問,除了ftp,nginx等,undertow 也是一個不錯的選擇,作為java開發,服務搭建非常簡便
服務搭建
創建一個maven quick-start 項目,並在pom中引入undertow,參考pom配置:
<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>com.iflytek</groupId>
<artifactId>fileserver</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>fileserver</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>io.undertow</groupId>
<artifactId>undertow-core</artifactId>
<version>2.0.22.Final</version>
</dependency>
</dependencies>
</project>
以下是我的項目結構:
其中FileServer 代碼如下:
package com.iflytek.fileserver;
import java.io.File;
import io.undertow.Handlers;
import io.undertow.Undertow;
import io.undertow.server.handlers.resource.PathResourceManager;
public class FileServer {
public static void main(String[] args) {
File file = new File("/");
Undertow server = Undertow.builder().addHttpListener(8080, "localhost")
.setHandler(Handlers.resource(new PathResourceManager(file.toPath(), 100))
.setDirectoryListingEnabled(true))
.build();
server.start();
}
}
好了!運行main函數,打開瀏覽器訪問 http://localhost:8080
簡單的幾行代碼,搞定!