Ignoring web.xml when loading a WAR file with Jett

2019-08-11 08:24发布

问题:

I'm trying a self-executable WAR package with Jetty. It configures with web.xml by default. If a run-time option is given, I wanted to override web.xml by Java code-level configuration with ServletContextHandler#addServlet, #addEventListener, and ...

Can I ignore web.xml while loading a WAR package?


% java -jar foobar.jar  # Use web.xml
% java -jar foobar.jar --customize=something  # Use Java code to configure

// Example

WebAppContext webapp = new WebAppContext();
webapp.setWar(warLocation.toExternalForm());
webapp.setContextPath("/");
if ( /* has run-time options */ ) {
  webapp.setWar(warLocation.toExternalForm()); // But, no load web.xml!
  // Emulates web.xml.
  webapp.addEventListener(...);
  webapp.setInitParameter("resteasy.role.based.security", "true");
  webapp.addFilter(...);
} else {
  webapp.setWar(warLocation.toExternalForm()); // Loading web.xml.
}

Additional Question:

Before server.start() is called, classes under WEB-INF/ are not loaded. Can I do some configuration webapp.something() with some classes under WEB-INF/? (E.g. extend WebInfConfiguration or do a similar class-loading that WebInfConfiguration does?)

For example, I'd like to do something like:

  • webapp.addEventListener(new SomeClassUnderWebInf()));
  • webapp.addEventListener(someInjector.inject(SomeClassUnderWebInf.class));

before server.start().

回答1:

Handle the WebAppContext Configuration yourself.

Eg:

private static class SelfConfiguration extends AbstractConfiguration
{
    @Override
    public void configure(WebAppContext context) throws Exception
    {
        // Emulates web.xml.
        webapp.addEventListener(...);
        webapp.setInitParameter("resteasy.role.based.security", "true");
        webapp.addFilter(...);
    }
}

public static void main(String[] args) throws Exception
{
    Server server = new Server(8080);

    WebAppContext webapp = new WebAppContext();
    webapp.setContextPath("/");
    if (useWebXml)
    {
        webapp.setConfigurationClasses(WebAppContext.getDefaultConfigurationClasses());
    } 
    else 
    {
        webapp.setConfigurations(new Configuration[] { 
            new SelfConfiguration() 
        });
    }
    webapp.setWar("path/to/my/test.war");
    webapp.setParentLoaderPriority(true);
    server.setHandler(webapp);
    server.start();
    server.join();
}