简体   繁体   中英

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.

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); }); }); 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM