views:

477

answers:

1

How to assign a value from JavaScript to Java variable in the JSP page? Is it possible to do this?

The following is the javascript function:

function loadGroupMembers(beanArrayVal){
    document.getElementById("beanVal").value=beanArrayVal;

   ------------I have mentioned my requirement below --------------

   %%%%%%%%%%%%%%%

   int beanArrVal =beanArrayVal ;

   %%%%%%%%%%%%%%

   ( or )

   %%%%%%%%%%

   c:set  var="beanvalue" value="${beanArrayVal}"

   %%%%%%%%%%%%%

}

Even I have assigned that beanArrayVal value in hidden input field too using id beanVal in the same above mentioned function. It's good enough even if is possible to assign value from this hidden field to JSTL variable.

+1  A: 

JS runs at the client machine. Java runs at the server machine. The only communication tool between those is HTTP. Java/JSP can generate/produce a HTML page and send it from server to client as a HTTP response, thus it can easily (pre)set Javascript variables by simply generating them as-is in the JSP template. But the other way round really requires a HTTP request from the client to the server. You can invoke HTTP requests synchronously by clicking a link or submitting a form, either manually or with little help of Javascript like link.click() or form.submit(). You can also invoke HTTP requests asynchronously with help of Ajaxical powers.

Long story short: let JS set it as a (hidden) input value / request parameter and send it to the server side by submitting the form with the (hidden) input value, or by invoking a link with the request parameter, or by firing an ajax request with a query string.

To learn more about the wall between Java/JSP and Javascript, you may find this article useful as well: Java/JSP/JSF and JavaScript.

Hope this clears a lot of things up and opens a new world for you.

BalusC