Undertow use as a simple web file server

Undertow is based on java nio web server, used widely, providing built-in PathResourceManager, can be used to directly access the file system; if you have a need to provide external access to the file, in addition to ftp, nginx, etc., undertow is also a good choice, as the java development, service is very simple to build

Services set up

Create a maven quick-start projects, and introduce undertow in the pom, pom reference configuration:

<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>

Here's my project structure:

Wherein FileServer code is as follows:

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();
    }
}

All right! Run the main function, open the browser to access http: // localhost: 8080

Simple few lines of code to get!

Guess you like

Origin www.cnblogs.com/ljgeng/p/11239345.html