user3578739
user3578739

Reputation: 35

What is the best way to communicate between a jsp page and a Servlet?

I'm making a dynamic web project in Eclipse and cannot figure out how to send a request from the user (via a button click) to a servlet that will perform some operation (including a database lookup) and then populate a webpage with the formatted results. I have all database lookup functions created. What is the best way to do this? I only really need one String to be passed back to the servlet, which will be the "category" of books that i wish to return as an ArrayList. Some sources seem to indicate that a jsp page should not even be used for relaying information to a servlet so I am very confused.

Upvotes: 2

Views: 1689

Answers (2)

MaVRoSCy
MaVRoSCy

Reputation: 17839

There are several ways to do this:

  1. Form Submit

    <form action="/myServlet" method="post">
        <input type="text" name="category" id="category"/>
        <input type="submit" value="submit" id="btnSubmit"/>
    

    And then in your servlet code (doPost()):

    String category = request.getParameter("category");
    
  2. Using ajax (jQuery ajax is much cleaner)

    $.ajax({
        method: "POST",
        url: "/myServlet",
        data: { category: $("#category").val()} //post category field
    }).done(function( msg ) {
        alert( msg ); //alert html returned from servlet 
    });
    
  3. JQuery Ajax (get)

    $("btnSubmit").click(function(event){
        event.preventDefault();
        $.get("/myServlet", function(data, status){
            alert("Data: " + data + "\nStatus: " + status);
        }); 
    });
    

Upvotes: 4

Sergio Vilchis
Sergio Vilchis

Reputation: 322

You can send your "category" parameter writting it in the URL : Servlet/?category=scifi and use request.getParameter("category"); in the doGet method.

Upvotes: 1

Related Questions