Friday, June 29, 2012

Create A parameterized bean using request parameter for JSF

Suppose you have a page project.xhtml. If the request is project.xhtml?project=myproject, you retrieve the 'myproject' Project instance and let user to modify it. If the request is request.xhtml with no query parameter, you instantiate a new Project object and let user edit and add it. How can you do this in J2EE platform?

I used to do this using a PhaseListener. The PhaseListener will inspect the request parameter and create the bean directly or using BeanManager from CDI.  However, producer method in CDI provides a good alternative.

class ProjectEditor

@Inject @EdittableProject Project project;

Project getProject()
 Object tobj = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap()
        if (tobj==null)
            return new Project();
        } else
            return findedProject;

public Project getProject()
 return project;

Here I use an qualifier @EdittableProject so that I make sure project from the producer method are used.

For the producer method, I give @Dependent scope explicitly to make sure there is  no client proxy wrapper around the return object.

After this I can reference the project in project.xhtml like this #{projectEditor.project}

No comments:

Post a Comment