How can I initiate `genericBean` with some managed bean as a default value at the beginning of an application?
If I had a generic bean in a JSF page. Like this:
<h:outputLabel value="#{genericBean.content}"/>
and this bean was not a managed bean, i.e. in faces-config there were only 2 managed beans :
<managed-bean>
<managed-bean-name>bean1</managed-bean-name>
<managed-bean-class>mb.Bean1</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
<managed-bean>
<managed-bean-name>bean2</managed-bean-name>
<managed-bean-class>mb.Bean2</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
and if both of these beans had a method getContent() :
public class Bean1{
public String get开发者_如何学编程Content(){
return "Content of Bean 1";
}
}
and
public class Bean2{
public String getContent(){
return "Content of Bean 2";
}
}
then I could change genericBean with the one of them :
Bean1 bean1 = new Bean1();
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("genericBean", bean1);
or
Bean2 bean2 = new Bean2();
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("genericBean", bean2);
according some business logic.
As you see I am using genericBean
just as a label in faces context. Now my question is: How can I initiate genericBean
with a bean1
as a default value at the beginning of an application?
Thanks.
You could use an application scoped (managed) bean and set the default value for your generic bean in the constructor.
You can use ServletContextListener
to achieve this
public class CustomApplicationContextListener implements ServletContextListener {
private static final String FOO = "foo";
public void contextInitialized(ServletContextEvent event) {
Bean1 bean1 = new Bean1();
event.getServletContext().setAttribute("genericBean", bean1 );
}
public void contextDestroyed(ServletContextEvent event) {
event.getServletContext().removeAttribute("genericBean");
}
}
web.xml
<listener>
<listener-class>com.yourpackage.CustomApplicationContextListener</listener-class>
</listener>
You should use an application scoped bean in jsf 2.0 style and mark it as eager
@ManagedBean(name="genericBean", eager=true)
@ApplicationScoped
public class GenericBean {
...
}
精彩评论