首页

基于Undertow实现FileServer文件应用服务器功能代码示例

标签:undertow,FileServer,文件资源服务器,fileserver     发布时间:2018-05-07   

一、前言

基于Undertow的io.undertow.Undertow、io.undertow.server.handlers.resource.PathResourceManager、io.undertow.Handlers.resource定义实现Web的文件资源服务器FileServer,详情参见代码示例部分(项目主要依赖xnio-api-3.3.0.Final.jar [更多其他版本]、xnio-nio-3.3.0.Final.jar包 [更多其他版本] )。

二、源码说明

1.FileServer服务类

package test.undertow;@b@@b@import io.undertow.Undertow;@b@import io.undertow.server.handlers.resource.PathResourceManager;@b@import java.nio.file.Paths;@b@import static io.undertow.Handlers.resource;@b@ @b@@UndertowExample("File Serving")@b@public class FileServer {@b@@b@    public static void main(final String[] args) {@b@        Undertow server = Undertow.builder()@b@                .addHttpListener(8080, "localhost")@b@                .setHandler(resource(new PathResourceManager(Paths.get(System.getProperty("user.home")), 100))@b@                        .setDirectoryListingEnabled(true))@b@                .build();@b@        server.start();@b@    }@b@@b@}
package test.undertow;@b@@b@import java.lang.annotation.ElementType;@b@import java.lang.annotation.Retention;@b@import java.lang.annotation.RetentionPolicy;@b@import java.lang.annotation.Target;@b@@b@@Retention(RetentionPolicy.RUNTIME)@b@@Target(ElementType.TYPE)@b@public @interface UndertowExample {@b@    String value();@b@    String location() default "http://localhost:8080";@b@}

2.测试运行效果如下图所示

基于Undertow实现FileServer文件应用服务器功能代码示例