JSF教程 – JSF注入托管Bean示例
下面的代码显示了如何做bean注入。
我们首先定义一个消息bean,它有一个string属性存储信息。
@ManagedBean(name="message") @SessionScoped public class MessageBean implements Serializable { private static final long serialVersionUID = 1L; private String sayWelcome = "Welcome to JSF 2.0";
然后我们定义另一个托管bean并注入MessageBean @ManagedProperty
注释。
@ManagedBean @SessionScoped public class UserBean implements Serializable { private static final long serialVersionUID = 1L; @ManagedProperty(value="#{message}") private MessageBean messageBean; public void setMessageBean(MessageBean messageBean) { this.messageBean = messageBean; }
例子
下面的代码来自UserBean.java。
package cn.w3cschool.common; import java.io.Serializable; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.SessionScoped; @ManagedBean @SessionScoped public class UserBean implements Serializable { private static final long serialVersionUID = 1L; @ManagedProperty(value="#{message}") private MessageBean messageBean; public void setMessageBean(MessageBean messageBean) { this.messageBean = messageBean; } private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSayWelcome(){ //check if null? if("".equals(name) || name ==null){ return ""; }else{ return messageBean.getSayWelcome() + name; } } }
以下代码来自demo.xhtml。
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html"> <h:body> <h:form> <h:inputText id="name" value="#{userBean.name}"></h:inputText> <h:commandButton value="Welcome Me"> <f:ajax execute="name" render="output" /> </h:commandButton> <h2><h:outputText id="output" value="#{userBean.sayWelcome}" /></h2> </h:form> </h:body> </html>
下面的代码来自MessageBean.java。
package cn.w3cschool.common; import java.io.Serializable; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; @ManagedBean(name="message") @SessionScoped public class MessageBean implements Serializable { private static final long serialVersionUID = 1L; private String sayWelcome = "Welcome to JSF 2.0"; public String getSayWelcome() { return sayWelcome; } public void setSayWelcome(String sayWelcome) { this.sayWelcome = sayWelcome; } }
Download Inject-Managed-Beans.zip
跑步
将生成的WAR文件从目标文件夹复制到Tomcat部署文件夹并运行Tomcat-Install-folder / bin / startup.bat。
Tomcat完成启动后,在浏览器地址栏中键入以下URL。
http://localhost:8080/simple-webapp/demo.xhtml