Starting up embedded jetty server for a JAR file

时光总嘲笑我的痴心妄想 提交于 2019-11-29 10:11:06

I'm not sure, if the WebAppContext of Jetty can be used with PathMatchingResourcePatternResolver!

In one of my projects I solved this problem by writing my own javax.servlet.Filter, which loads the requested resources by Class#getResourceAsStream. Class#getResourceAsStream reads resources from inside a jars as well as inside a resource path (e.g. maven).

Hope this tip is helpful for you, cheers Thilo

I believe, I faced a similar problem a couple months ago, I used Jetty v9.4.12.v20180830.

Here is my solution:

If you have the following generated JAR structure:

 app.jar
   +----- com /
   |        +--- ( classes ... )
   |
   +----- config /
   |        |
   |        +--- display.properties
   |
   +----- webapp /
            |
            +--- index.html

Then the following code will refer to the correct folder:

ServletContextHandler webappContext = new ServletContextHandler(ServletContextHandler.SESSIONS);  
URL webRootLocation = YourJettyStarterClass.class.getResource("/webapp/index.html");  
URI webRootUri = URI.create(webRootLocation.toURI().toASCIIString().replaceFirst("/index.html$", "/"));  
webappContext.setContextPath("/");
webappContext.setBaseResource(Resource.newResource(webRootUri));
webappContext.setWelcomeFiles(new String[] { "index.html" });  

The important part:

URL webRootLocation = YourJettyStarterClass.class.getResource("/webapp/index.html");   
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!