Silk0vsky Silk0vsky - 4 months ago 57
Java Question

Java web.xml location and jetty

I'm trying to understand the way we should configure the web application.
Now i have a simple gradle project with embedded jetty

layout structure

Dependencies:

dependencies {
compile('org.eclipse.jetty:jetty-servlet:9.3.10.v20160621')
compile('org.eclipse.jetty:jetty-webapp:9.3.10.v20160621')

testCompile group: 'junit', name: 'junit', version: '4.11'
}


Application main:

package test;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;

public class App {
public static void main(String[] args) throws Exception {

System.out.println(">> Running");
WebAppContext webAppContext = new WebAppContext();
webAppContext.setDescriptor("src/main/resources/WEB-INF/web.xml");
webAppContext.setResourceBase("/");
webAppContext.setContextPath("/");

Server server = new Server(8080);
server.setHandler(webAppContext);
server.start();
server.join();
}
}


In web.xml I defined only ServletContextListener implementation to find if it was catched with application.

My problem is:
webAppContext.setDescriptor("src/main/resources/WEB-INF/web.xml")

Jetty can find web.xml only with this weird location path.

Why do I need to target it from project folder?
If I run jar task with gradle the wouldn't be any src directory inside the jar.

Is exist a way to something like:
App.class.getResource("/WEB-INF/web.xml")
and load web.xml related to classpath?

Answer

Seems it was some class loaders issue.

After some further searches I ended with next solution:

public class App {
    private static final String WEBAPP_RESOURCES_LOCATION = "webapp";

    public static void main(String[] args) throws Exception {
        System.out.println(">> Running");

        WebAppContext webAppContext = new WebAppContext();
        webAppContext.setContextPath("/");

        URL webAppDir = Thread.currentThread().getContextClassLoader().getResource(WEBAPP_RESOURCES_LOCATION);
        webAppContext.setResourceBase(webAppDir.toURI().toString());

        // if setDescriptor set null or don't used jetty looking for /WEB-INF/web.xml under resource base 
//        webAppContext.setDescriptor(webAppDir.toURI().toString() + "web.xml");

        Server server = new Server(8080);
        server.setHandler(webAppContext);
        server.start();
        server.join();
    }
}

Thanks github user arey for the examle examle