Undertow 作為簡單的web文件服務器使用


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

簡單的幾行代碼,搞定!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM