How can i change the value of java variable using javascript?
Suppose i have declare a variable in java servlet like int x=0;
so now i want to change its value to 1 on onclick event of any button on servlet how can i do that?
Thanks
NOTE! You should not hold state inside of your servlet, as it may be used by multiple threads (multiple users). Such values should be stored in the Session object, or in some backend - a database for instance.
Now back to your question: Your browser JavaScript code, cannot operate directly on Java code executing on the server. However, you could bind a click event handler to your buttons, and execute an AJAX call to your servlet increasing this value. See this answer for an example of how to do it with JQuery.
JavaScript executes at client side , and Servlets written in Java executes at server side.
Both are different environments. If you want to change the state of the server side object from JavaScript, you should be doing it through AJAX.
Question: Suppose i have declare a variable in java servlet like int x=0; so now i want to change its value to 1 on onclick event of any button on servlet how can i do that?
Answer: You should not have variable in Servlet. Because Servlets are not Thread Safe. I think you just want to change the state of the client, which might be stored as session.
You can not change the value of java variable using javascript directly . what you can do fist get the javascript variable in request parameter by putting hidden filed or pass it to url and then get value using `rwquest.getParameter("field").
Javascript runs on client browser so you can't get it directly.
I don't understand why everyone is saying you cannot do this.
Of course you can. I have called java methods from javascript many times using Remote API in JavaScript. If for instance using Seam, you can do it like this: http://docs.jboss.com/seam/latest/reference/en-US/html/remoting.html
Here the OP must find out which framework he wants to use, or which remoting technology that is best suited for OP
For instance, you call a java method that takes int as parameter, and you apply the value to the variable.