Marty
Marty

Reputation: 3

JSP Run a method on button click

I looked up and even there are similar questions and answers I cannot seem to understand how. The problem is that when I run a jsp file which has a JavaScript, it runs when I start the page instead on the set form onClick="..."; Also, I know I am using scriptlets that is discouraged but I am completely new to jsp so I don't know how to make classes for it. I am using Netbeans.

<script LANGUAGE="JavaScript">
function connect(){
<% ConnectToServer(); %>
};

function startApp(){
<% InvokeStartApplicationInstance(); %>   
<% InvokeStartApplication(); %>  
};

function stopApp(){
<% InvokeShutdownApplication(); %> 
};
</script>

<FORM name="myform">
    <INPUT NAME="connectbtn" TYPE="button" VALUE="Connect" onClick="connect()">
     <INPUT NAME="startbtn" TYPE="button" VALUE="Start" onClick="startApp()">
      <INPUT NAME="stopbtn" TYPE="button" VALUE="Stop" onClick="stopApp()">
</FORM>

ConnectToServer(); and other methods in JavaScript are the methods I included on the same jsp page between <%! and %>

The thing is that those methods work but JavaScript runs all on pageload regardless. So, for example, if the last one is <% InvokeShutdownApplication(); %> in the JavaScript it will do this one so it will not be able to do start. I need it to work onClick.

I have no idea how to call a method directly with Java. the method below does not work:

<INPUT NAME="connectbtn" TYPE="button" VALUE="Connect" onClick="<% ConnectToServer(); %>">

Any help would be appreciated cause I need to do a mbeans (which is java-based) app web-based and it is driving me bonkers.

Upvotes: 0

Views: 10022

Answers (1)

kahowell
kahowell

Reputation: 30146

The reason this happens is that as the JSP is parsed, the embedded Java code is run and the results are substituted into the final HTML. What you want here is to do an Ajax call back to the server to get it to invoke the method you want. It's going to be a little more complex than what you have I'm afraid. I'd recommend looking at jQuery and its Ajax API.

Upvotes: 1

Related Questions