Search code examples
jsfparametersparameter-passingmanaged-bean

JSF request scope with get parameter


i know there are many similar threads but no like mine:

I have a requestscope bean:

@ManagedBean
@RequestScoped
public class Bean implements Serializable{
    private String username = ""; //managed by textbox
    private String password = ""; //managed by textbox

    private String id ="-";

    //Load the Parameter as usual:
    @PostConstruct
    public void fetchParams(){
        System.out.println("FETCH PARAMS");
        FacesContext facesContext = FacesContext.getCurrentInstance();
        String id = facesContext.getExternalContext().getRequestParameterMap().get("id");
        if(id == null || id.length() == 0) return;
        setId(id);
    }

    // getters & setters

    public void doSomething(){ //executed when clicked on the sumbit-button on the jsf-site
        StaticFunctions.doSomething(this);
    }
}

The code does following: it retrieves the get-parameter "id" and saves it into String id (confirmed by string.out....).

But when the method doSomething() is executed and the previously stored "id" is read and returns "-" (like nothing happened).

why is this so?


Solution

  • Your ManagedBean is @RequestScoped and will be destroyed at the end of the request. When doSomething() is executed the user submitted the form and started a new request. So you should see "FETCH PARAMS" twice in the console because two Beans are created but for the second request id is null.

    You can find a detailed explanation about the four JSF-Scopes here.