Jetty实战之 嵌入式运行Jetty实现简单文件服务器
发布日期:2021-06-30 18:38:30
浏览次数:2
分类:技术文章
本文共 2465 字,大约阅读时间需要 8 分钟。
原文链接:http://blog.csdn.net/kongxx/article/details/7224423
对于嵌入式运行Jetty,可以通过简单的一些代码实现一个简单的文件服务器的功能,如下:
package com.google.code.garbagecan.jettystudy.sample3; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.DefaultHandler; import org.eclipse.jetty.server.handler.HandlerList; import org.eclipse.jetty.server.handler.ResourceHandler; public class FileServer { public static void main(String[] args) throws Exception { Server server = new Server(8080); ResourceHandler resourceHandler = new ResourceHandler(); resourceHandler.setDirectoriesListed(true); resourceHandler.setResourceBase("E:/share"); resourceHandler.setStylesheet(""); HandlerList handlers = new HandlerList(); handlers.setHandlers(new Handler[] { resourceHandler, new DefaultHandler() }); server.setHandler(handlers); server.start(); server.join(); } }这里使用了Jetty自带的ResourceHandler类来处理所有的请求,这个类指定了资源路径,并且允许列出目录和文件,这里需要注意的是“resourceHandler.setStylesheet("");”,如果没有这一行代码的话,在请求资源的时候后台总是会不停的抛出NullPointerException。
运行FileServer类,访问http://localhost:8080/就可以看到“E:/share”下的所有文件和目录了。
上面是通过编码的方式实现了简单的文件服务器,其实Jetty也可以通过配置文件的方式实现文件服务器的功能,如下:
创建一个配置文件com/google/code/garbagecan/jettystudy/sample3/fileserver.xml,内容如下:
创建一个java类FileServerWithXml8080 true E:/share .
package com.google.code.garbagecan.jettystudy.sample3; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.util.resource.Resource; import org.eclipse.jetty.xml.XmlConfiguration; public class FileServerWithXml { public static void main(String[] args) throws Exception { Resource resource = Resource.newClassPathResource("/com/google/code/garbagecan/jettystudy/sample3/fileserver.xml"); XmlConfiguration configuration = new XmlConfiguration(resource.getInputStream()); Server server = (Server) configuration.configure(); server.start(); server.join(); } }运行FileServerWithXml类,访问http://localhost:8080/也可以看到“E:/share”下的所有文件和目录了。
转载地址:https://linqiarui.blog.csdn.net/article/details/50783582 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
做的很好,不错不错
[***.243.131.199]2024年04月21日 06时43分23秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
记一次曲折的Debug经历
2019-04-30
Impala支持Google云存储开发笔记
2019-04-30
如何在Apache JIRA中搜索issue
2019-04-30
scrapy 排错记录
2019-04-30
ACM路上的一大失误
2019-04-30
HDOJ2049 不容易系列之(4)——考新郎
2019-04-30
CodeForces 248B - Chilly Willy - 找规律
2019-04-30
POJ-2418 Hardwood Species(Trie树)(map)
2019-04-30
HDU-4300 Clairewd’s message + 4333(扩展KMP)
2019-04-30
HDU 1592 Half of and a Half(高精度)
2019-04-30
POJ-3304 Segments(计算几何)
2019-04-30
UVA-11538 Chess Queen(数学)
2019-04-30
UVA-11401 Triangle Counting(数学优化)
2019-04-30
Codeforces Round #369 (Div. 2)
2019-04-30
UVA 11426 GCD - Extreme (II)(欧拉函数)
2019-04-30
HDU-2838 Cow Sorting(树状数组)
2019-04-30
POJ-2299 Ultra-QuickSort(树状数组)(离散化)
2019-04-30
基于SSM的兼职论坛系统的设计与实现
2019-04-30