简体   繁体   English

在jsp页面和Servlet之间进行通信的最佳方法是什么?

[英]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. 我正在Eclipse中创建一个动态Web项目,但无法弄清楚如何将来自用户的请求(通过单击按钮)发送到Servlet,该Servlet将执行某些操作(包括数据库查找),然后使用格式化的内容填充网页结果。 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. 我只真正需要一个String传递回servlet,这就是我希望作为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. 一些消息似乎表明,甚至不应该将jsp页面用于将信息中继到servlet,所以我很困惑。

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()): 然后在您的servlet代码(doPost())中:

     String category = request.getParameter("category"); 
  2. Using ajax (jQuery ajax is much cleaner) 使用ajax(jQuery ajax更干净)

     $.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) jQuery Ajax(获取)

     $("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"); 您可以将“类别”参数发送到URL中:Servlet /?category = scifi并使用request.getParameter(“ category”); in the doGet method. 在doGet方法中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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