我有一个带有视图范围bean和会话范围bean的JSF Web应用程序。我想从视图bean修改会话bean的成员,并且我从一个着名的JSF人员那里得到了this指南,但是如果没有运行时异常,我似乎无法让它工作。对托管会话bean的引用,“home”在引用时为null,类似于this question,除了我已经遵循接受的答案的建议。
package brian.canadaShipping;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
@ManagedBean(name= "requestBean")
@ViewScoped
public class CpstcRequestBean implements Serializable {
@ManagedProperty(value="#{home}")
private CpstcHomeBean homeBean;
public CpstcHomeBean getHomeBean() {
return homeBean;
}
public void setHomeBean(CpstcHomeBean homeBean) {
this.homeBean = homeBean;
}
private static final long serialVersionUID = -5066913533772933899L;
public String testVar = "hello world";
private boolean displayOutput = false;
public boolean isDisplayOutput() {
return displayOutput;
}
public void setDisplayOutput(boolean displayOutput) {
this.displayOutput = displayOutput;
}
public String getTestVar() {
return testVar;
}
public void setTestVar(String testVar) {
this.testVar = testVar;
}
public CpstcRequestBean()
{
System.out.println("TEST: " + homeBean.toString());
System.out.println("Hello, ResuestBean!");
}
}
我的“home”bean的第一位如下:
@ManagedBean(name= "home")
@SessionScoped
public class CpstcHomeBean implements Serializable {
...
更新:我遵循了乔丹的建议,我在视图范围内的bean中有以下内容:
@ManagedBean(name= "requestBean")
@ViewScoped
public class CpstcRequestBean implements Serializable {
@Inject @Named("home") CpstcHomeBean homeBean;
public CpstcHomeBean getHomeBean() {
return homeBean;
}
public void setHomeBean(CpstcHomeBean homeBean) {
this.homeBean = homeBean;
}
public CpstcRequestBean()
{
System.out.println("TEST: " + homeBean.toString());
System.out.println("Hello, ResuestBean!");
}
...
以及我在会话范围内的bean:
@Named("home")
@SessionScoped
public class CpstcHomeBean implements Serializable {
...
但我的“home”bean引用仍为null。有什么想法吗?
更新2:事实证明,您必须在两个类中使用@Named,而不仅仅是注入的类。我的网络应用程序现在加载但有些元素是空白的。在我的控制台日志中,我看到,“Target Unreachable,标识符'home'已解析为null。”我正在运行Tomcat 7,如果这会影响事情的话。有什么想法吗?
答案 0 :(得分:0)
您可以将会话bean的@ManagedBean更改为@Named,然后将其注入到视图范围的bean中,或者您可以像这样引用会话bean:
FacesContext fc = FacesContext.getCurrentInstance()
private CpstcHomeBean homeBean = (CpstcHomeBean) fc.getApplication().evaluateExpressionGet(fc, "#{home}", CpstcHomeBean.class);