The following code shows how to do bean injection.
We define a message bean first, it has a string property which stores the message.
@ManagedBean(name="message") @SessionScoped public class MessageBean implements Serializable { private static final long serialVersionUID = 1L; private String sayWelcome = "Welcome to JSF 2.0";
Then we define another managed bean and inject the MessageBean with
@ManagedProperty
annotation.
@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; }
The following code is from UserBean.java.
package com.java2s.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; } } }
The following code is from 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>
The following code is from MessageBean.java.
package com.java2s.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; } }
Copy the generated WAR file from the target folder to Tomcat deployment folder and run Tomcat-Install-folder/bin/startup.bat.
After Tomcat finish starting, type the following URL in the browser address bar.
http://localhost:8080/simple-webapp/demo.xhtml