Calling an action on GET Request using JSF viewAction

This example shows how to call an action on a GET request using JSF viewAction. Since JSF 2.2 we have a new element called <f:viewAction> which is a child element of <f:metadata> . This allows us to call an action on GET requests.

JSF Managed Bean

Just a normal managed bean as you can see later the index.xhtml page is specifying a JSF viewAction and maps the action attribut to the loadUserById() method.

package com.memorynotfound;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

public class UserBean {

    private Integer id;
    private User currentUser;

     * pre loads the user from a repository
     * @return current page
    public String loadUserById(){
        currentUser = UserRepository.findUser(id);
        return null;

    public Integer getId() {
        return id;

    public void setId(Integer id) { = id;

    public User getCurrentUser() {
        return currentUser;


Class representing a user

package com.memorynotfound;

public class User {

    private Integer id;
    private String name;

    public User(Integer id, String name) { = id; = name;

    public Integer getId() {
        return id;

    public String getName() {
        return name;

User repository

Simple repository to lookup a user

package com.memorynotfound;

public class UserRepository {

    final static User[] users = {
            new User(0, "user a"),
            new User(1, "user b"),
            new User(2, "user c")

    public static User findUser(Integer id){
        for (User user : users){
            if (user.getId().equals(id)){
                return user;
        return null;

Mapping a JSF viewAction to a managed bean

The JSF viewAction allows us to execute a method on GET request of a page. This action has the ability to implicitly navigate to another page.

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html>
<html xmlns=""
        <f:viewParam name="id" value="#{}" />
        <f:viewAction action="#{userBean.loadUserById}"/>

    <h1>JSF ViewAction: execute method on GET Requests</h1>

    <h:panelGrid columns="2">
        <h:outputLabel value="User id to load: "/>
        <h:outputText value="#{}"/>

        <h:outputLabel value="Loaded user id: "/>
        <h:outputText value="#{}"/>

        <h:outputLabel value="Loaded user name: "/>
        <h:outputText value="#{}"/>



URL: http://localhost:8080/jsf-viewaction/result.xhtml?id=1

jsf viewaction get request



You may also like...

  • Samadi

    Thank you