Passing parameters from JS to JSF (client to server)

Working in the same application with a client-side and a server-side language always raises the same question: how to pass parameters between them. In this recipe we will pass parameters from JS (client side) to JSF (server side), while in the next recipe we will reverse this task.

Getting ready

We have developed this recipe with NetBeans 6.8, JSF 2.0, and GlassFish v3. The JSF 2.0 classes were obtained from the NetBeans JSF 2.0 bundled library.

How to do it...

In this recipe we will present two examples, and we start by passing a parameter from JavaScript to a JSF managed bean, through a JSF inputText component. The idea is to allow to a JS function to submit the form (the form contains the inputText) and, before submitting, to set the inputText's value attribute to the desired value. For this we implement the onclick event of a JSF button. Instead of submitting the form, this button will actually call the JS function, which modifies the value inputText's value attribute and submits the form. Here it is the code:

<script type="text/javascript" language="javascript">
function setTextValue(){
document.getElementById('formId:textId').value = 'JavaScript_1';
document.getElementById('formId').submit();
}
</script>
…
<h:form id="formId">
<h:inputText id="textId" value="#{bean.text}" />
<h:commandButton id="btn_1_Id" value="Submit (use setTextValue)"
action="#{bean.action}" onclick="setTextValue();" />
</h:form>

In the second example, we pass the variable on the GET request using the JS window.location object. Here it is the code:

function setWindowLocation(){
var param = 'JavaScript_2';
window.location =
'http://localhost:8080/Pass_param_from_JS_to_JSF
/newpage.xhtml?p=' + escape(param);
}
…
<h:outputText value="Parameter on GET reuqest" />
<h:commandButton id="btn_2_Id" value="Submit (use window.location)"
onclick="setWindowLocation();" />

Getting the variables passed on an HTTP GET request in the JSF is presented in the Passing parameters with HTTP GET within the URL recipe.

How it works...

The main trick here is that the form submission in not performed by JSF; it is performed by JS, which has the "power" to modify the values of the JSF components and also knows how to submit a JSF form. In practice, the user is not aware that JS is involved in the equation.

See also

The code bundled with this book contains a complete example of this recipe. The project can be opened with NetBeans 6.8 and it is named: Pass_param_from_JS_to_JSF.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset