In JSF, “f:setPropertyActionListener” tag is allow you to set a value directly into the property of your backing bean. For example,

<h:commandButton action="#{user.outcome}" value="Submit">
    <f:setPropertyActionListener target="#{user.username}" value="mkyong" />
</h:commandButton>

In above JSF code snippets, if the button is clicked, it will set the “mkyong” value to the “username” property via setUsername() method.

@ManagedBean(name="user")
@SessionScoped
public class UserBean{
 
	public String username;
 
	public void setUsername(String username) {
		this.username = username;
	}
 
}

JSF f:setPropertyActionListener example

Ok, let’s see a full example in JSF 2.0.

1. Managed Bean

A super simple managed bean named “user”.

package com.mkyong;
 
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
 
@ManagedBean(name="user")
@SessionScoped
public class UserBean{
 
	public String username;
 
	public String outcome(){
		return "result";
	}
 
	public String getUsername() {
		return username;
	}
 
	public void setUsername(String username) {
		this.username = username;
	}
 
}

2. JSF Page

JSF page to show the use of “f:setPropertyActionListener” to set a value “mkyong” directly into the property “username” of your backing bean.

default.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>
 
    	<h1>JSF 2 setPropertyActionListener example</h1>
 
	<h:form id="form">
 
	  <h:commandButton action="#{user.outcome}" value="Click Me">
 
	      <f:setPropertyActionListener target="#{user.username}" value="mkyong" />
 
	  </h:commandButton>
 
	</h:form>
 
    </h:body>
</html>

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>
 
    	<h1>JSF 2 setPropertyActionListener example</h1>
 
	#{user.username}
 
    </h:body>
 
</html>

3. Demo

Here’s the result after button is clicked.

jsf2-setPropertyActionListener-example

Download Source Code

Reference

  1. JSF 2 setPropertyActionListener JavaDoc
Note : You can find more similar articles at - JSF 2 Tutorials