java – WebAppContext将参数传递给servlet构造函数

前端之家收集整理的这篇文章主要介绍了java – WebAppContext将参数传递给servlet构造函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我在主类中有webAppContext,我有一个servlet,它有WebServlet注释和带args的构造函数.我怎么能把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中:

Metadata-complete="false"
        version="3.0">

Servlet的:

@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));
    }
}
最佳答案
好吧,据我所知,您使用JavaSE和嵌入式Jetty创建了Web应用程序.您可以使用注释将servlet添加到服务器.
然后Jetty创建它调用默认构造函数的servlet.
但是你需要以某种方式将你在main()中创建的对象的链接传递给你的servlet.

所以,有几种解决方案:

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

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

原文链接:https://www.f2er.com/java/437193.html

猜你在找的Java相关文章