Ignoring web.xml when loading a WAR file with Jetty

。_饼干妹妹 提交于 2019-12-24 08:30:37

问题


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();
}


来源:https://stackoverflow.com/questions/30391418/ignoring-web-xml-when-loading-a-war-file-with-jetty

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