Reputation: 111
I need to call a certain java method when I click a button on a JSP page. How do I do this? I've tried writing a scriptlet into the button's onclick where I create an instance of the class and then use it to call the method, but it doesn't work.
Upvotes: 0
Views: 1404
Reputation: 2621
Adding to the previous answers that Java code executes on the server-side, not in your browser, if you do have Java code that you want to execute on the server you can post from an HTML form or Ajax call back to a servlet, some endpoint/service or use some other web framework, and execute the code from there.
Upvotes: 0
Reputation: 17745
What you are trying to do is not possible. The button being clicked is an action that happens on the client, away from any server code. The client doesn't know anything about your java code.
JSP is an acronym for Java Server Pages. It's a technology that provides you the means to combine static html and java code. When this is compiled, it will become nothing more than a servlet, a .class
file. This outputs html when it's called. This html is then handed to the client. The content handed to the client has no java logic in it. All the java code was used for the generation of this content, while still on the server. After it's generated, it's done, now you only have html, css, javascript.
What you need to do is to use some javascript. Assign a click listener to the button you need and make an AJAX call to the server. Depending on the response you get (from the server to the client), you apply some changes, again, with javascript.
There are many ways to apply a listener for the button in question.
Inline function
<button onclick="myFunction()">Click me</button>
Event listener
document.getElementById("myBtn").addEventListener("click", displayDate);
Of course you can use js libraries like jQuery, that provide you hassle free functionality in a few lines of code.
If you know only java, and want to get rid off as much of the other technologies as possible, then you could check Google Web Toolkit. Basically is a compiler for java to javascript code.
Upvotes: 1