Search code examples
javajspservletsscriptlet

invoking java scriptlet in JSP using HTML


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


Solution

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

    <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>