1

I want to execute a jsp function when a submit button is clicked. Here's what I'm trying to do:

<form>
    <input type="text" id="input">
    <input type="submit" onClick="(I want the function to be here)">
</form>

<@!
public static void get(){
    String s = request.getParameter("input");
    System.out.println(s);
}

(I have simplified the code, if you don't understand please let me know.)

I don't really know if this is possible in anyway, I have been searching and I have seen suggestions on similar cases of using AJAX, but I'm not familiar with it and if there is a simpler solution it would be so much easier.

Edit: I just wanted to specify that the function I'm trying to call isn't this simple, I simplified. The actual function uses code that only Java can run (using a Java library).

Adrià
  • 207
  • 1
  • 4
  • 12

3 Answers3

1

This is how you can make a simple ajax request from your jsp file to some java code:

Returning String as plain text

The jsp page:

  <!DOCTYPE html>
    <html lang="en">
        <head>
            <title>SO question 4112686</title>
            <script src="http://code.jquery.com/jquery-latest.min.js"></script>
            <script>
                $(document).on("click", "#somebutton", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
                    $.get("someservlet", function(responseText) {   // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response text...
                        $("#somediv").text(responseText);           // Locate HTML DOM element with ID "somediv" and set its text content with the response text.
                    });
                });
            </script>
        </head>
        <body>
            <button id="somebutton">press here</button>
            <div id="somediv"></div>
        </body>
    </html>

Servlet doGet() method:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String text = "some text";

   //you can write whatever java code you want to have here, and you can pass the results to the jsp file through the response writer. (text) This will only work from simple strings. If you want to pass more complicated information like lists or objects you will need to convert it to a json object

    response.setContentType("text/plain");  // Set content type of the response so that jQuery knows what it can expect.
    response.setCharacterEncoding("UTF-8"); // You want world domination, huh?
    response.getWriter().write(text);       // Write response body.
}

If you want to do it in a form you can do it like this:

Ajaxifying an existing form

<form id="someform" action="someservlet" method="post">
    <input type="text" name="foo" />
    <input type="text" name="bar" />
    <input type="text" name="baz" />
    <input type="submit" name="submit" value="Submit" />
</form>

<script>

$(document).on("submit", "#someform", function(event) {
    var $form = $(this);

    $.post($form.attr("action"), $form.serialize(), function(response) {
        // ...
    });

    event.preventDefault(); // Important! Prevents submitting the form.
});

</script>

Servlet:

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String foo = request.getParameter("foo");
    String bar = request.getParameter("bar");
    String baz = request.getParameter("baz");

    //do some java stuff here

   //then return whatever you want
response.setContentType("text/plain");  
response.setCharacterEncoding("UTF-8"); /
response.getWriter().write("hello world");     
}

Examples taken from: How to use Servlets and Ajax

Jonathan Laliberte
  • 2,672
  • 4
  • 19
  • 44
  • This worked. The first example. But changing `some text` in the `text` variable doesn't actually change the result. I still get `some text` printed. – Adrià Nov 02 '18 at 15:53
  • are you doing this with a servlet then? You managed to get rid of that error? how so? If changing the text variable didn't do anything i think it's because of your server configuration, try restarting the server – Jonathan Laliberte Nov 02 '18 at 17:16
  • I had indeed created a Dynamic Web Project, I just had to import the library. Everytime i run this code, "some text" is displayed, and it doesn't change no matter what. – Adrià Nov 02 '18 at 18:16
  • hmm that's very strange, it shouldn't be doing that. I'm pretty sure it has something to do with the server not refreshing the java files. It would be so much easier if i could just see why what you're doing exactly. You should download teamviewer, it would take my like 5-10mins max to figure it out and help you set this up – Jonathan Laliberte Nov 02 '18 at 18:18
  • On the second example, is it supposed to display "Hello World"? – Adrià Nov 02 '18 at 18:29
  • yes, i removed the text variable in that example. not sure why – Jonathan Laliberte Nov 02 '18 at 18:34
  • Still displays "some text" – Adrià Nov 02 '18 at 18:35
  • hmm yeah that's pretty strange, there's no reason why it should stay as "some text" other than your server not updating the java code (or it hasn't been saved). You tried restarting your server and cleaning the project ye? – Jonathan Laliberte Nov 02 '18 at 18:39
  • Yes, none of it works... I even deleted the server and added a new one, nothing – Adrià Nov 02 '18 at 18:45
  • Comparing to another Dynamic Web Project i have, I have noticed that there is a section on the other one that I don't have on mine. (Actual mine is _Projecte_) [here](https://imgur.com/Vlo9VLJ) – Adrià Nov 02 '18 at 18:52
  • hmm yeah i don't understand at all why you would be seeing this behaviour, i would have to look at your code to understand it properly, that image doesn't explain why – Jonathan Laliberte Nov 02 '18 at 19:08
  • I don't know if [this](https://mega.nz/#!Yp8X0QgQ) or [this](https://mega.nz/#!Mx1nSQxJ) helps – Adrià Nov 02 '18 at 19:57
  • says i need a decryption key to access those folder – Jonathan Laliberte Nov 02 '18 at 20:15
  • oops wait. [here](https://mega.nz/#!Yp8X0QgQ!gRpIiAenrvLXqaQVdnSXsTC5_sck_EARyEnU116lp6Q) you go and [here](https://mega.nz/#!Mx1nSQxJ!dUNXkNFiCvWf91sKJXb4C8uJbDHV7q7ogZeT0ZG1IxA) you go! – Adrià Nov 02 '18 at 20:17
  • nah .rar and .war isn't gonna help. you would have to send me the project folder as a zip. Then i can just open it up in eclipse – Jonathan Laliberte Nov 02 '18 at 20:19
  • [here](https://mega.nz/#!w5V0GKBS!8n8mwLhcOqWvz_Cg0jGnmw26zuKyuHhGqCyaTcx1V4w) you go – Adrià Nov 02 '18 at 20:44
  • ok first, add the javax-servlet-api-3.0.1.jar into lib folder inside WEB-INF – Jonathan Laliberte Nov 02 '18 at 21:14
  • then what kind of server are you running for this application? so i can run it as well – Jonathan Laliberte Nov 02 '18 at 21:18
  • the reason why it doesn't change is because in your post method before you write() you have this: `doGet(request, response);` and you doGet method is blank. Remove this `doGet(request, response);` from doPost – Jonathan Laliberte Nov 02 '18 at 21:21
  • I'm running it on Tomcat v9.0 – Adrià Nov 02 '18 at 21:34
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/183033/discussion-between-adria-and-jonathan-laliberte). – Adrià Nov 02 '18 at 21:36
0

The onClick() function is meant to be used for JavaScript or JavaScript frameworks, you can do what you are trying to do with JS.

In JS create a function with a parameter, then, the onClick() will look like this

onClick="(myFunction(variableName))"

Inside myFunction(variableName) should look like this

myFunction(variableName){ alert("The variable is: " +variableName); }

alert("The variable is: " +variableName); will create like a pop up at the top of the webpage showing your variable value.

SammeAyala
  • 79
  • 1
  • 4
  • What I'm trying to do is calling a jsp function, that I can only do writing it in Java. The code is simplified. – Adrià Nov 02 '18 at 12:39
0

You can try with this code:

if(request.getParameter("btnSubmit")!=null) //btnSubmit is the name of your button, not id of that button.
{
java.util.Date d = new java.util.Date();
System.out.println(d.toString()); 
}

<input type="submit" id="btnSubmit" name="btnSubmit" value="Execute Test"/>

Source: onClick function call using scriptlet

AbA2L
  • 110
  • 7