Question

I wonder what is the common way to use get request, parameters and ajax requests together with JSF?

What I want to achieve is to pass an id parameter to a JSF page, retrieve the entity with the given parameter from the database and display the entity on the JSF page. Then, I want to make some changes to the entity and populate it back to the database (via ajax).

I stuck on the step, where I want to populate the changes back to the database. Here is what I have so far:

I have a very simple JSF page and a controller (ManagedBean).

JSF page

<h:body>
    <h:form id="myForm">
        <p:messages />
        <h:panelGrid columns="3">
            <h:outputLabel value="#{requestController.id}" />
            <p:commandButton value="Update" action="#{requestController.updateEntity}" update="myForm" />
        </h:panelGrid>
    </h:form>
</h:body>

Controller

@Component("requestController")
@Scope("request")
public class RequestController {

@Value("#{request.getParameter('id')}")
private String id;

private String entity;

@PostConstruct
public void init() {
    if(id == null || id.equals("")) {
        entity = "Entity not found";
    }
    else if("1".equals(id)) {
        entity = "FirstEntity";
    }
    else {
        entity = "SecondEntity";
    }
}

public String getEntity() {
    return entity;
}

public void updateEntity() {
    entity += "_updated";
}

public String getId() {
    return id;
}
}

I can open the JSF page with an id parameter and the entity will be displayed correctly. But, when I click on the update button, the Controller will be newly instantiated and the id parameter is gone.

What is the common way to handle request parameters together with ajax requests in JSF?

Was it helpful?

Solution

Solution is to add the request parameter at every request in the page. This can be done with the <f:param> tag.

So, to make the above code work, you just have to include the initial request parameter to the command button:

<p:commandButton value="Update" action="#{requestController.updateEntity}" update="myForm" >
    <f:param name="id" value="#{requestController.id}" />
</p:commandButton>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top