I am trying to find a way to invoke a piece of java code
within the JSP using HTML form
<form method="get" action="invokeMe()">
<input type="submit" value="click to submit" />
</form>
<%
private void invokeMe(){
out.println("He invoked me. I am happy!");
}
%>
the above code is within the JSP. I want this run the scriptlet upon submit
I know the code looks very bad, but I just want to grasp the concept... and how to go about it.
thanks
You can't do this since JSP rendering happens on server-side and client would never receive the Java code (ie. the
invokeMe()
function) in the returned HTML. It wouldn't know what to do with Java code at runtime, anyway!What's more,
<form>
tag doesn't invoke functions, it sends an HTTPform
to the URL specified inaction
attribute.You can use Ajax to submit form to servlet and evaluate java code, but stay on the same window.
JSP page:
Not possible. When the form is submitted, it sends a request to the server. You have 2 options:
Have the server perform the desired action when the it receives the request sent by the form
or
Use Javascript to perform the desired action on the client:
Sorry,not possible.
Jsp lies on
server
side andhtml
plays onclient side
unless without making arequest
you cannot do this :)you cannot write a
java method
inscriptlet
. Because atcompilation
time code inscriptlet
becomes part ofservice
method. Hence method within a method is wrong.How ever you can write
java methods
withininit tag
and can call fromscriptlet
like below code.