加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 01:03:36 所属栏目:Java 来源:网络整理
导读:我在主类中有webAppContext,我有一个servlet,它有WebServlet注释和带args的构造函数.我怎么能把args从Main类传递给Servlet? Main.java: String webappDirLocation = "src/main/java/frontend/webapp/";WebAppContext webAppContext = new WebAppContext();

我在主类中有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中:

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中.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读