0

I have a jsp linked to a javabean, with some code that decreases a variable by one within the bean using jsp:setproperty everytime a button is clicked (it's inside a javascript function that runs when you click a button).

However, the code runs every time the page is refreshed, not when the function is called. I'm pretty sure I know why (jsp is run on the server, javascript is run in the client, therefore js can't interface with the java code), but I don't know a way to actually do something like that properly.

I'm a javabean newbie so I'm probably overlooking something.

Thanks.

EDIT: I ended up doing something completely different and using this to make a hidden form in javascript that submits info to a different jsp and redirects back. It works kinda like sharing a javascript variable with jsp code when I can just grab it from a URL parameter.

Community
  • 1
  • 1
Toby Bloem
  • 76
  • 1
  • 9

1 Answers1

0

You are right. JavaScript runs in a different execution environment than the JSP. To be more accurate, your JSP is compiled into a Java class (by the container) that has a similar structure to a servlet. All the JSP code that you write is translated into Java and put into the _jspService() method of the Java class. When the browser makes a request for the JSP page (you click on a link or refresh the browser) the container calls the _jspService() method of the Java class, executes all the translated JSP code and returns a response to the browser, normally in the form of a web page.

So if your JSP contains code that increases a variable by one this will only execute when you click a link to the JSP or refresh the page.

There are two possible solutions:

  1. When you click the button make the JavaScript refresh the page.
  2. Use AJAX to call a servlet that returns just the updated value of the variable. Then use JavaScript to replace the value in the web with the value returned by the AJAX call.

This question might help with the AJAX: ajax call to servlet and redirect to jsp

Good luck.

Community
  • 1
  • 1
Alex Theedom
  • 1,499
  • 13
  • 16