我遇到类似于this post的问题以及来自@BalusC的3个解决方案的答案,但是:
我的代码如下:
index.xhtml
:
<?xml version="1.0" encoding="windows-1256" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Insert title here</title>
</h:head>
<h:body>
<h:form>
<p:panelMenu id="westMenu">
<p:submenu id="sub1" label="System Monitor">
<p:menuitem id="menu1" value="live monitoring"
action="#{menusBean.activateMenu('sub1_menu1')}"
update=":centerPane,westMenu"
disabled="#{menusBean.active['sub1_menu1']}" />
<p:menuitem id="menu2" value="reports"
action="#{menusBean.activateMenu('sub1_menu2')}"
update=":centerPane,westMenu"
disabled="#{menusBean.active['sub1_menu2']}" />
</p:submenu>
<p:submenu id="sub2" label="Charging System Nodes" />
<p:submenu id="sub3" label="Additional Nodes" />
</p:panelMenu>
</h:form>
<h:panelGroup id="centerPane">
...
</h:panelGroup>
</h:body>
</html>
MenusBean.java
:
package menus;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.view.ViewScoped;
@ManagedBean
@ViewScoped
public class MenusBean implements Serializable{
private static final long serialVersionUID = -7793281454064343472L;
private String mainPage="sub1_menu1";
private Map<String, Boolean> active;
public MenusBean(){
System.out.println("MenusBean created");
active = new HashMap<>();
active.put(mainPage, true);
active.put("sub1_menu2", false);
}
public boolean activateMenu(String page){
active.put(mainPage, false);
active.put(page, true);
mainPage = page;
for (Map.Entry<String, Boolean> e : active.entrySet())
System.out.println(e.getKey()+":"+e.getValue());
return true;
}
public Map<String, Boolean> getActive() {
return active;
}
}
执行时,我得到:
MenusBean created MenusBean created MenusBean created
这是如何引起的?如何解决?
答案 0 :(得分:34)
此,
import javax.faces.view.ViewScoped;
是JSF 2.2-introduced CDI-specific注释,旨在与CDI特定的bean管理注释@Named
结合使用。
但是,您正在使用特定于JSF的bean管理批注@ManagedBean
。
import javax.faces.bean.ManagedBean;
然后,您应该使用同一javax.faces.bean
package提供的任何范围。右@ViewScoped
就在那边:
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
@ManagedBean
@ViewScoped
public class MenusBean implements Serializable{
如果使用了错误的组合,则bean的行为与@RequestScoped
bean相同,并在每次调用时重新创建。
或者,如果您的环境支持CDI(GlassFish / JBoss / TomEE with Weld,OpenWebBeans等),那么您也可以用@ManagedBean
替换@Named
:
import javax.inject.Named;
import javax.faces.view.ViewScoped;
@Named
@ViewScoped
public class MenusBean implements Serializable{
建议转到CDI。特定于JSF的bean管理注释是未来JSF / Java EE版本中的弃用词,因为一切都在向CDI缓慢移动/统一。