简体   繁体   English

如何在 Tomcat 7 中以编程方式配置 ServletContextListener?

[英]How to configure a ServletContextListener programmatically in Tomcat 7?

I'd like to configure one or more ServletContextListener's programmatically, that is, without configuring them via web.xml.我想以编程方式配置一个或多个 ServletContextListener,也就是说,不通过 web.xml 配置它们。 I'm currently doing something similar by adding servlets and filters programmatically.我目前正在通过以编程方式添加 servlet 和过滤器来做类似的事情。

Is this possible?这可能吗? If so, could someone provide an example?如果是这样,有人可以提供一个例子吗?

With Tomcat 7 you have two options to avoid web.xml.使用 Tomcat 7,您有两种选择可以避免 web.xml。 The first is to use the @WebListener annotation but I suspect that isn't quite what you want.第一个是使用 @WebListener 注释,但我怀疑这不是你想要的。 The second it so use a ServletContainerInitializer (SCI).第二个它使用 ServletContainerInitializer (SCI)。 For an exmaple, see how Tomcat's WebSocket SCI does it.举个例子,看看Tomcat 的 WebSocket SCI是如何做到的。 That SCI does a lot of things.那个 SCI 做了很多事情。 The relevant line for you is servletContext.addListener(new WsContextListener());与您相关的行是servletContext.addListener(new WsContextListener());

Note that an SCI uses the services API to register itself .请注意,SCI 使用服务 API 来注册自己

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM