Embedded Jetty handling urls to serve content

冷暖自知 提交于 2019-12-02 10:03:44

General Note: ResourceHandler is not for use with an application that has a ServletContext.
The ResourceHandler is ultra-primitive (and very naive) and intended only to support web applications that use raw Jetty handlers only.
Do not mix ResourceHandler with ContextHandler, ServletContextHandler, or WebAppContext.

Based on what you have asked, I think you want this ...

URL urlToWebDir = findUrlTo("/web");
ServletContextHandler servletContextHandler = 
    new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);
servletContextHandler.setContextPath("/");
servletContextHandler.setWelcomeFiles(new String[] { "index.html" });
servletContextHandler.setBaseResource(Resource.newResource(urlToWebDir));
servletContextHandler.addServlet(DefaultServlet.class, "/");

ErrorPageErrorHandler errorMapper = new ErrorPageErrorHandler();
errorMapper.addErrorPage(404,"/"); // map all 404's to root (aka /index.html)
servletContextHandler.setErrorHandler(errorMapper);

This is a simpler setup for your "/web" path requirement.

The BaseResource is the URL (it can be a jar:file:// or file:// URL reference) which is used by the DefaultServlet to serve your static content.

So that if a request comes in on /image.png then {baseResource}/image.png is served (and a request on /icons/avatar.gif is served from {baseResource}/icons/avatar.gif

The WelcomeFiles sets up the index.html resolving, so that a request on / results in serving file {baseResource}/index.html. (also works if request is /alternate/path/deep/in/your/tree/ then /alternate/path/deep/in/your/tree/index.html is served (if it exists).

Bonus note: DefaultServlet supports pre-compressed static content serving. Meaning if you gzip your content and keep a copy of it along-side, then the compressed version is served to your users if their browser says it supports compressed responses. (example: request for /js/hugelib.js with old browser that doesn't support compressed responses, then {baseResource}/js/hugelib.js is served. But if browser supports compressed responses, then {baseResource}/js/hugelib.js.gz is served instead)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!