How to get Javascript parameters or values from JSF ManagedBean

Our current project right now uses JSF and we are trying to use Primefaces and utilize its features. One function we are trying to use is the RemoteCommand, in which you can pass Javascript parameters directly to a ManagedBean java class. We had a difficulty implementing this at first as Primefaces’ showcase hasn’t given us that much demo on how to extend its use. After some time, I was able to make it work, and here is how I did it:

 

You have to do changes to 3 files, your javascript, jsf(xhtml) file, and the ManagedBean java class:

  • In your js file, add a sample function:
    function testCommand() {
    	getjsParams([{name:'param1', value:'value1'}, {name:'param2', value:'value2'}]);
    }

     

  • In your ManagedBean java class, add:
    public void getParams(){
    	FacesContext context = FacesContext.getCurrentInstance();
    	Map<String,String> params = context.getExternalContext.getRequestParameterMap();
    	String param1 = params.get("param1");
    	String param2 = params.get("param2");
     
    	System.out.println(param1);
    	System.out.println(param2);
    }
  • Then lastly, in your xhtml:
    <h:form>
    	<p:remoteCommand name="getjsParams" action="#{yourMB.getParams}" />
    	<p:commandButton type="button" value="Test Remote Command" onclick="testCommand();" />
    </h:form>

Output on terminal will be “value1” and “value2”.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s