Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/401.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何将类添加到web应用程序的应用程序范围_Java_Jsf_Servlets - Fatal编程技术网

Java 如何将类添加到web应用程序的应用程序范围

Java 如何将类添加到web应用程序的应用程序范围,java,jsf,servlets,Java,Jsf,Servlets,需要向ServletContext添加一个Java类(在我的项目中名为HistoryBean)。我不想在项目中的不同servlet中创建HistoryBean类的新实例。我想从ServletContext获取它。请帮我提些建议。您可以在ServletContextListener中这样做: public void contextInitialized(ServletContextEvent e) { e.getServletContext().setAttribute("history

需要向ServletContext添加一个Java类(在我的项目中名为HistoryBean)。我不想在项目中的不同servlet中创建HistoryBean类的新实例。我想从ServletContext获取它。请帮我提些建议。

您可以在
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注释。