【问题标题】:Loading web fragment when running embedded jetty运行嵌入式码头时加载网页片段
【发布时间】:2016-11-14 09:14:35
【问题描述】:

在测试环境中,我尝试使用一些应用程序运行嵌入式码头。该应用程序依赖于some-dependency,它在META-INF 文件夹中指定了一个web-fragemnt.xml。我正在尝试像这样加载片段:

public static void someMain(...) {
    server = new Server(port);
    final WebAppContext context = new WebAppContext();
    addFragmentIfExists(context);
    context.setContextPath("/");
    context.setParentLoaderPriority(true);
    context.setResourceBase(pathToWebapp);
    server.setHandler(context);
}

private void addFragmentIfExists(final WebAppContext context) {
    final Optional<URL> url = Stream.of(((URLClassLoader) ClassLoader.getSystemClassLoader()).getURLs())
            .filter(u -> u.toString().contains("some-dependency")).findFirst();
    url.ifPresent(u -> {
        try {
            context.getMetaData().addFragment(newResource(u),
                    newResource(new File(u.getPath(), "META-INF/web-fragment.xml")));
        } catch (Exception e) {
            ...
        }
    });
}

调试时,我可以看到片段在server.handler.metadata.webFragments{Roots,NameMap,ResourceMap} 下加载,但在server.handler.{filters,servlets} 下我看不到该片段中声明的过滤器和servlet 我究竟做错了什么? 另外,是否有一种不那么笨拙的方式来加载片段?我在类路径中也有一个弹簧网络片段,所以如果我只是尝试从类路径加载它会加载弹簧一个

【问题讨论】:

    标签: java jetty embedded-jetty


    【解决方案1】:

    将 web-fragment jar 放入你的pathToWebapp + "/WEB-INF/lib/" 目录,并设置配置以使用 Web Fragments。

    例如:

        Server server = new Server(8080);
    
        Configuration.ClassList classlist = Configuration.ClassList
                .setServerDefault(server);
        classlist.addAfter("org.eclipse.jetty.webapp.FragmentConfiguration",
                "org.eclipse.jetty.plus.webapp.EnvConfiguration",
                "org.eclipse.jetty.plus.webapp.PlusConfiguration");
        classlist.addBefore(
                "org.eclipse.jetty.webapp.JettyWebXmlConfiguration",
                "org.eclipse.jetty.annotations.AnnotationConfiguration");
    
        WebAppContext context = new WebAppContext();
        context.setContextPath("/");
        // ... etc ...
    

    【讨论】:

    • 谢谢,我试试看,我不知道为什么要更改配置类的顺序,反正它们都加载了,这里有新的类吗?此外,此解决方案不够通用,因为当处于战争形式时 jar 已经在该目录中,但是在 IDE 中运行测试时,片段位于依赖项目目标文件夹中的类目录中
    • 我正在使用码头:8.1.5.v20120716 我的类路径中没有这些配置类
    猜你喜欢
    • 1970-01-01
    • 2012-05-31
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 2017-02-16
    • 1970-01-01
    • 2018-03-13
    • 2011-05-25
    相关资源
    最近更新 更多