ofloflofl
ofloflofl

Reputation: 205

onClick jsp button function

I want to trigger a function when I click on a button in jsp file. I write this code:

    <%!public void PrintOut(){
System.out.println("okk");
} %>
      <body>
 <button onclick="PrintOut()"> print OK</button>
  </body>

but it doesn't work. and when I use the

 `<script>
function myFunction(){<%
System.out.println("OKK");%>}
</script>`

it execute before I click on button.

Upvotes: 1

Views: 18767

Answers (1)

JB Nizet
JB Nizet

Reputation: 691715

Here's how a JSP works:

  • A request is sent from a browser in Paris to a JSP, on a server in San Francisco
  • The server executes the JSP. The JSP produces HTML, potentially containing JavaScript code, and sends this HTML to the browser in the HTTP response
  • The browser, in Paris, displays the page
  • Some time later, the button is clicked. The JavaScript code is executed, in the browser, in Paris. The server, in San Francisco, doesn't have any idea of what's happening in the browser in Paris. It could even be stopped.

That little story to explain you that JavaScript and Java are two different languages, and that the Java code is executed on a server, long before the JavaScript code is executed on the browser. What you're doing makes no sense at all. If you want something to happen on the server in San Francisco when a button is clicked in the browser in Paris, then you must send an HTTP request to the server (by submitting a form, or by using AJAX).

Upvotes: 11

Related Questions