【问题标题】:WebAppContext pass argument to servlet constructorWebAppContext 将参数传递给 servlet 构造函数
【发布时间】:2015-09-12 01:35:15
【问题描述】:

我在主类中有 webAppContext,我有一个 servlet,它有 WebServlet 注释和带参数的构造函数。如何将 args 从 Main 类传递给 Servlet?

Main.java:

String webappDirLocation = "src/main/java/frontend/webapp/";
WebAppContext webAppContext = new WebAppContext();
webAppContext.setResourceBase("public_html");
webAppContext.setContextPath("/");
webAppContext.setDescriptor(webappDirLocation + "WEB-INF/web.xml");
webAppContext.setConfigurations(new Configuration[]{
                new AnnotationConfiguration(), new WebXmlConfiguration(),
                new WebInfConfiguration(),
                new PlusConfiguration(),
                new MetaInfConfiguration(),
                new FragmentConfiguration(),
                new EnvConfiguration()}
);
webAppContext.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", ".*/classes/.*");
webAppContext.setParentLoaderPriority(true);

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
        metadata-complete="false"
        version="3.0">
</web-app>

小服务程序:

@WebServlet(name = "WebSocketGameServlet", urlPatterns = {"/gameplay"})
public class WebSocketGameServlet extends WebSocketServlet {
    static final Logger logger = LogManager.getLogger(GameWebSocket.class);
    private final static int IDLE_TIME = 6000 * 1000;
    private AccountService accountService;
    private Game game;
    private WebSocketService webSocketService;

    public WebSocketGameServlet(AccountService accountService, Game game, WebSocketService webSocketService) {
        this.accountService = accountService;
        this.game = game;
        this.webSocketService = webSocketService;
    }

    @Override
    public void configure(WebSocketServletFactory factory) {
        factory.getPolicy().setIdleTimeout(IDLE_TIME);
        factory.setCreator(new GameWebSocketCreator(accountService, game, webSocketService));
    }
}

【问题讨论】:

  • 您应该使用 EJB 注入,因为您决定使用 IoC(控制反转)。

标签: java jetty servlet-3.0


【解决方案1】:

嗯,据我了解,您使用 JavaSE 和嵌入式 Jetty 创建了 Web 应用程序。您使用注释将 servlet 添加到您的服务器。 然后 Jetty 创建调用默认构造函数的 servlet。 但是您需要以某种方式将指向您在 main() 中创建的对象的链接传递给您的 servlet。

所以,有几种解决方案:

  1. 创建您自己的“dependency injection”:将单例类上下文添加到您的应用程序。在 main() 中,将您的服务放到 Context 的 Map&lt;Class&lt;?&gt;, Object&gt; 中。并将它们放入 servlet。
  2. 使用依赖注入框架。喜欢Spring
  3. 转到 J2EE 并使用 EJB。在这种情况下,您需要忘记自己的main() 并由网络服务器管理。

附:码头服务器有方法addBean(...)。您可以将“bean”添加到服务器(在代码或配置中)。但据我所知,不可能在 servlet 中获取这个 bean。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 2015-10-11
    • 2013-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多