We can use h:attribute tag to pass a attribute value to a component, or a parameter to a component via action listener.
The following code shows how to use h:attribute tag.
<h:commandButton id="submit" actionListener="#{userData.attributeListener}" action="result"> <f:attribute name="value" value="Show Message" /> <f:attribute name="username" value="JSF 2.0 User" /> </h:commandButton>
Attribute | Description |
---|---|
name | The name of the attribute to set |
value | The value of the attribute |
The following code is from UserBean.java.
package com.java2s.common; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.event.ActionEvent; @ManagedBean(name="user") @SessionScoped public class UserBean{ public String nickname; public void attrListener(ActionEvent event){ nickname = (String)event.getComponent().getAttributes().get("username"); } public String outcome(){ return "result"; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } }
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:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core"> <h:body> <h:form id="form"> <h:commandButton action="#{user.outcome}" actionListener="#{user.attrListener}"> <f:attribute name="username" value="java2s.com" /> <f:attribute name="value" value="Click Me" /> </h:commandButton> </h:form> </h:body> </html>
The following code is from result.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:h="http://java.sun.com/jsf/html"> <h:body> #{user.nickname} </h:body> </html>
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