WildFly - getting resource from WAR

后端 未结 7 734
既然无缘
既然无缘 2020-12-21 00:13

I am using the following method to get a resource from WAR file in WildFly:

this.getClass().getResource(relativePath)

It works when the app

7条回答
  •  情深已故
    2020-12-21 00:37

    I ran into this same problem, and rather than define the resource as a shared module, I ended up working around this by using a ServletContextListener in my WAR.

    In the contextInitialized method, I got the ServletContext from the ServletContextEvent and used its getResource("/WEB-INF/myResource") to get the URL to the resource inside my WAR file. It appears that in the ServletContextListener, the .getResource() method resolves as expected rather than to the "/modules/system/layers/base/org/jboss/as/ejb3/main/timers/" url. That URL can then be stored in the ServletContext for later use by your servlets or in an injected ApplicationScoped CDI bean.

    @WebListener
    public class ServletInitializer implements ServletContextListener {
    
        @Override
        public void contextInitialized(ServletContextEvent sce) {
            try {
                final ServletContext context = sce.getServletContext();
                final URL resourceUrl = context.getResource("/WEB-INF/myResource");
                context.setAttribute("myResourceURL", resourceUrl);
            } catch (final MalformedURLException e) {
                throw new AssertionError("Resource not available in WAR file", e);
            }
        }
    
        @Override
        public void contextDestroyed(ServletContextEvent sce) {}
    }
    

    or

    @WebListener
    public class ServletInitializer implements ServletContextListener {
    
        @Inject
        private SomeApplicationScopedBean myBean;
    
        @Override
        public void contextInitialized(ServletContextEvent sce) {
            try {
                final ServletContext context = sce.getServletContext();
                final URL resourceUrl = context.getResource("/WEB-INF/myResource");
                myBean.setResourceUrl(resourceUrl);
            } catch (final MalformedURLException e) {
                throw new AssertionError("Resource not available in WAR file", e);
            }  
        }
    
        @Override
        public void contextDestroyed(ServletContextEvent sce) {}
    }
    

提交回复
热议问题