使用特殊的自动启动servlet在启动时初始化并共享应用程序数据我需要获得一些配置,并连接到某个地方的外部资源/对象/系统,并将其存储在应用程序范围内。我可以看到设置应用程序的两种方法:覆盖init()在现有的servlet和必需的代码中,并将所有构造的对象保存在同一个servlet中。具有某种初始化servlet,并使用其init()去做这项工作。然后将创建的对象存储在ServletContext与我的其他servlet共享它。以上哪种方法更好?是否有更好的方法在servlet之间共享对象?直接给他们打电话吗.?
1 回答
一只斗牛犬
TA贡献1784条经验 获得超2个赞
CDI/JSF/EJB不可用?使用 ServletContextListener
@WebListenerpublic class Config implements ServletContextListener { public void contextInitialized(ServletContextEvent event) { // Do stuff during webapp's startup. } public void contextDestroyed(ServletContextEvent event) { // Do stuff during webapp's shutdown. }}
@WebListener
/WEB-INF/web.xml
<listener> <listener-class>com.example.Config</listener-class></listener>
ServletContext#setAttribute()
#getAttribute()
.
public void contextInitialized(ServletContextEvent event) { event.getServletContext().setAttribute("config", this); // ... }
protected void doGet(HttpServletRequest request, HttpServletResponse response) { Config config = (Config) getServletContext().getAttribute("config"); // ... }
${config}
有CDI吗?使用 @Observes
在……上面 ApplicationScoped.class
import javax.enterprise.context.ApplicationScoped;@ApplicationScopedpublic class Config { public void init(@Observes @Initialized(ApplicationScoped.class) ServletContext context) { // Do stuff during webapp's startup. } public void destroy(@Observes @Destroyed(ApplicationScoped.class) ServletContext context) { // Do stuff during webapp's shutdown. }}
@Inject
@Named
#{config}
JSF可用吗?使用 @ManagedBean(eager=true)
import javax.faces.bean.ManagedBeanimport javax.faces.bean.ApplicationScoped;@ManagedBean(eager=true)@ApplicationScopedpublic class Config { @PostConstruct public void init() { // Do stuff during webapp's startup. } @PreDestroy public void destroy() { // Do stuff during webapp's shutdown. }}
#{config}
EJB可用吗?考虑 @Startup
@Singleton
@Startup@Singletonpublic class Config { @PostConstruct public void init() { // Do stuff during webapp's startup. } @PreDestroy public void destroy() { // Do stuff during webapp's shutdown. }}
@EJB
@Singleton
另见:
添加回答
举报
0/150
提交
取消