invoking java scriptlet in JSP using HTML

2019-05-20 23:37发布

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

5条回答
三岁会撩人
2楼-- · 2019-05-21 00:15

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 HTTP form to the URL specified in action attribute.

查看更多
聊天终结者
3楼-- · 2019-05-21 00:16

You can use Ajax to submit form to servlet and evaluate java code, but stay on the same window.

JSP page:

<form method="get" action="invokeMe()" id="submit">

       <input type="submit" value="click to submit" />

</form>

<script>
    $(document).ready(function() {
        $("#submit").submit(function(event) {
            $.ajax({
                type : "POST",
                url : "your servlet here(for example: DeleteUser)",
                data : "id=" + id,
                success : function() {
                    alert("message");
                }
            });
            $('#submit').submit(); // if you want to submit form
        });
    });
</script>
查看更多
我想做一个坏孩纸
4楼-- · 2019-05-21 00:19

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:

 <form name="frm1" action="submit" onsubmit="invokeMe()"
 ...
 </form>

 <script>
 function invokeMe()
 {
 alert("He invoked me. I am happy!")
 }
 </script>
查看更多
冷血范
5楼-- · 2019-05-21 00:24

Sorry,not possible.

Jsp lies on server side and html plays on client side unless without making a request you cannot do this :)

查看更多
趁早两清
6楼-- · 2019-05-21 00:30

you cannot write a java method in scriptlet. Because at compilation time code in scriptlet becomes part of service method. Hence method within a method is wrong.

How ever you can write java methods within init tag and can call from scriptlet like below code.

<form method="get" action="">

       <input type="submit" value="click to submit" />

  </form>

    <%
        invokeMe();

     %>

  <%!
       private void invokeMe(){
       out.println("He invoked me. I am happy!");   
     }
   %>
查看更多
登录 后发表回答