Table of Contents

Pass parameters from one page to another in jsf

Intro

I've been looking around how to solve this typical problem: to pass one parameter from one page to other (for instance when we prompt the user to select one item on a list and, when clicking a button, switch to another page to edit this very item).

Despite the fact that the Internet is crowded with examples of how to pass parameters to and fro a bean and a page, I've don't see many examples of this, and the solutions I've found didn't satisfy me completely: first, because some of them use the faces-config.xml file and I don't use it much because all my beans are held by Spring, second, because these solution requires a configuration per navigation case, that it isn't very easy to do.

So, I've found this solution reading some hints of this article.

Step 1: the idea

I've avoided to pass the parameters in a request, or something like that: instead of this, I will save them in a session bean devoted to this.

Step 2: the bean to save the objects in session

public class SessionHelper implements Serializable
{
 
    public static Object getSessionMapValue(String key) 
    {
        return FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(key);
    }
 
    public static void setSessionMapValue(String key, Object value) 
    {
    	FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(key, value);
    }
}

Step 3: Page 1 saves the parameter

This is an example in a commandButton of Primefaces, but you can adapt to your library of preference:

	   <p:commandButton ajax="false"
	                   type="submit" 
	                   id="cmdModify" 
	                   value="Modificar"
	                   action="#{manageUsersForm.cmdModify}"
	                   disabled="#{!manageUsersForm.userSelected}"
	                   styleClass="right">
	      #{sessionHelper.setSessionMapValue('selectedUser',manageUsersForm.selectedUser)}
	   </p:commandButton>

Yes, I've called the sessionHelper.setSessionMapValue directly inside the commandButton tag and it seems to do the work. I thought that you have to use a faces tag or something like that, but it seems that it is not completely neccesary.

Step 4: Page 2 receives the parameter

Just simple as this:

 <h3><h:outputText value="#{sessionHelper.getSessionMapValue('selectedUser').username}"/></h3>

Look that I've passed through the session a complete object. Okay, it's not a recommendable practice unless you are completely sure that the objects implements Serializable (and the depending objects, of course), because otherwise you would run into problems in a clustered environment.

This particular example the object is an Hibernate entity object… Mmmm I think that if persisted in another computer could lead into problems, but I have to confess that I am not an expert in the field.