Jetty:使用WebAppProvider将主对象的对象传递给Servlet

时间:2018-04-27 19:10:50

标签: embedded-jetty jetty-9

我需要在main方法中传递一个来自嵌入式jetty代码的对象,以便在servlet中使用。

这是一个问题,因为WebAppContext中使用了单独的类加载器 - 否则我只会使用静态变量。

我的主要代码设置如下:

Server server = new Server(); 
// setup connectors here...
ContextHandlerCollection contexts = new ContextHandlerCollection();
RequestLogHandler requestLogHandler = new RequestLogHandler();
HandlerCollection handlers = new HandlerCollection();
handlers.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler });
server.setHandler(instrumentedHandler(handlers, metrics));

addRequestLogging(requestLogHandler);

DeploymentManager deploymentManager = new DeploymentManager();
deploymentManager.setContexts(contexts);

WebAppProvider webAppProvider = new WebAppProvider();
webAppProvider.setMonitoredDirName(jettyHome + "/webapps");
webAppProvider.setParentLoaderPriority(false);
webAppProvider.setExtractWars(true);
webAppProvider.setScanInterval(1);
webAppProvider.setDefaultsDescriptor(jettyHome + "/webdefault.xml");
webAppProvider.setConfigurationManager(new PropertiesConfigurationManager());

deploymentManager.addAppProvider(webAppProvider);
server.addBean(deploymentManager);
// Attempt to set the metrics on the server - but I can't access them in the Servlet
server.setAttribute(MetricRegistry.class.getName(), metrics);
server.start();
server.join();

我尝试了question中的一些内容,但它们没有用。具体来说,servlet上下文中没有设置org.eclipse.jetty.server.Server属性。

(具体来说,我试图在jetty对象上设置dropwizard指标,但我需要为我的应用程序的其余部分使用相同的MetricRegistry对象,以便我可以将所有指标和记者保持在一起)

1 个答案:

答案 0 :(得分:1)

使用DeploymentManager时,您无法在主开始代码期间访问WebAppContextServletContextHandlerContextHandler

您必须使用DeploymentManager中的工具来提供自定义AppLifeCycle.Binding,以便在部署阶段执行您需要执行的操作。

奖励是在热(重新)部署期间也能正常工作。

以下是来自embedded-jetty-cookbook

的嵌入式码头中此设置的工作示例

DeployWebApps.java

package org.eclipse.jetty.cookbook;

import java.io.File;
import java.io.FileNotFoundException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

import org.eclipse.jetty.deploy.App;
import org.eclipse.jetty.deploy.AppLifeCycle;
import org.eclipse.jetty.deploy.DeploymentManager;
import org.eclipse.jetty.deploy.graph.Node;
import org.eclipse.jetty.deploy.providers.WebAppProvider;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerCollection;

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

        ContextHandlerCollection contexts = new ContextHandlerCollection();
        HandlerCollection handlers = new HandlerCollection();

        handlers.setHandlers(new Handler[]{contexts, new DefaultHandler()});

        server.setHandler(handlers);

        Path confFile = Paths.get(System.getProperty("user.dir"), "example.conf");

        ContextAttributeCustomizer contextAttributeCustomizer = new ContextAttributeCustomizer();
        contextAttributeCustomizer.setAttribute("common.conf", confFile);

        DeploymentManager deploymentManager = new DeploymentManager();
        deploymentManager.setContexts(contexts);
        deploymentManager.addLifeCycleBinding(contextAttributeCustomizer);

        String jettyBaseProp = System.getProperty("jetty.base");
        if (jettyBaseProp == null)
        {
            throw new FileNotFoundException("Missing System Property 'jetty.base'");
        }
        Path jettyBase = new File(jettyBaseProp).toPath().toAbsolutePath();

        WebAppProvider webAppProvider = new WebAppProvider();
        webAppProvider.setMonitoredDirName(jettyBase.resolve("webapps").toString());

        deploymentManager.addAppProvider(webAppProvider);
        server.addBean(deploymentManager);

        // Lets dump the server after start.
        // We can look for the deployed contexts, along with an example of the
        // result of ContextAttributesCustomizer in the dump section for "Handler attributes"
        server.setDumpAfterStart(true);
        server.start();
        server.join();
    }

    public static class ContextAttributeCustomizer implements AppLifeCycle.Binding
    {
        public final Map<String, Object> attributes = new HashMap<>();

        public void setAttribute(String name, Object value)
        {
            this.attributes.put(name, value);
        }

        @Override
        public String[] getBindingTargets()
        {
            return new String[]{ AppLifeCycle.DEPLOYING };
        }

        @Override
        public void processBinding(Node node, App app) throws Exception
        {
            ContextHandler handler = app.getContextHandler();
            if (handler == null)
            {
                throw new NullPointerException("No Handler created for App: " + app);
            }
            attributes.forEach((name, value) -> handler.setAttribute(name, value));
        }
    }
}