Java 如何将类添加到web应用程序的应用程序范围
需要向ServletContext添加一个Java类(在我的项目中名为HistoryBean)。我不想在项目中的不同servlet中创建HistoryBean类的新实例。我想从ServletContext获取它。请帮我提些建议。您可以在Java 如何将类添加到web应用程序的应用程序范围,java,jsf,servlets,Java,Jsf,Servlets,需要向ServletContext添加一个Java类(在我的项目中名为HistoryBean)。我不想在项目中的不同servlet中创建HistoryBean类的新实例。我想从ServletContext获取它。请帮我提些建议。您可以在ServletContextListener中这样做: public void contextInitialized(ServletContextEvent e) { e.getServletContext().setAttribute("history
ServletContextListener
中这样做:
public void contextInitialized(ServletContextEvent e) {
e.getServletContext().setAttribute("historyBean", new HistoryBean());
}
使用
@WebListener
或web.xml中的。
注册您的侦听器。您可以在ServletContextListener中执行此操作:
public void contextInitialized(ServletContextEvent e) {
e.getServletContext().setAttribute("historyBean", new HistoryBean());
}
使用web.xml中的@WebListener
或。
注册您的侦听器。使用JSF时,只需将其注册为应用程序范围的bean即可
@ManagedBean(eager=true)
@ApplicationScoped
public class HistoryBean {
// ...
}
(注意,eager=true
,这会在webapp启动时自动构造bean,而不需要在某些视图或bean中引用它,您不需要使用ServletContextListener
)
这样,它不仅在JSF上下文中可用(通常的方式是{historyBean}
),而且在servlet中也可以作为servlet上下文属性使用,托管bean名称作为键,如下所示:
HistoryBean historyBean = (HistoryBean) getServletContext().getAttribute("historyBean");
在使用JSF时,只需将其注册为应用程序范围的bean
@ManagedBean(eager=true)
@ApplicationScoped
public class HistoryBean {
// ...
}
(注意,eager=true
,这会在webapp启动时自动构造bean,而不需要在某些视图或bean中引用它,您不需要使用ServletContextListener
)
这样,它不仅在JSF上下文中可用(通常的方式是{historyBean}
),而且在servlet中也可以作为servlet上下文属性使用,托管bean名称作为键,如下所示:
HistoryBean historyBean = (HistoryBean) getServletContext().getAttribute("historyBean");
谢谢波佐……我做到了。现在我正试图找出如何从我的servlet中的servlet上下文中获取它,以便我可以使用HistoryBean中的方法…….调用ctx.getAttribute(“HistoryBean”)
谢谢Bozho……我做到了。现在我正试图找出如何从我的servlet中的servlet上下文获取它,以便我可以使用HistoryBean中的方法…….调用ctx.getAttribute(“HistoryBean”)
,这些方法不是JPA注释。这些是JSF注释,而不是JPA注释。这些都是JSF注释。