将数据从JSP发送到servlet

时间:2014-07-02 12:53:39

标签: java javascript jsp servlets

以下是我的需求:

在jsp中,我填写了一个"表"使用javascript(我的第一个" tr"是标题,第二个" tr"是输入然后所有新的" tr"添加了javascript函数)

现在我想将表的值发送到servlet。 我不使用jquery框架

以下是我在js中所做的事情:

function test(){
    var strPar= "Blabla BLABLA BLA";
    var toServer = JSONObject.toJSONString(strPar);
    alert("TEST U MF !!!");
    var request = new XMLHttpRequest();
    request.open("POST", "http://localhost:8084/Calendar/Legal", true);
    request.send(toServer);
    alert("POUET !");
}

我似乎根本无法工作!此外,我不知道如何从servlet获取JSON对象?

public class LegalCalServlet extends HttpServlet {

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    System.out.println("TEST ");
    String output = request.getParameter("strPar");
    System.out.println(output);

}}

我非常感谢任何有关此事的帮助!

2 个答案:

答案 0 :(得分:0)

尝试在请求中添加标题 -

以下是从http://www.openjs.com/articles/ajax_xmlhttp_using_post.php

发布数据的示例
var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("POST", url, true);

//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

http.onreadystatechange = function() {//Call a function when the state changes.
    if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);
    }
}
http.send(params);

答案 1 :(得分:0)

使用:

 xmlhttp.open("POST","demo_post2.asp",true);
 xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
 xmlhttp.send("fname=Henry&lname=Ford");

您可以查看此网站中的示例和教程:http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp

var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
   xmlhttp=new XMLHttpRequest();
   }
 else
   {// code for IE6, IE5
   xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
   }
 xmlhttp.onreadystatechange=function()
   {
   if (xmlhttp.readyState==4 && xmlhttp.status==200)
     {
     document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
     }
   }
 xmlhttp.open("POST","demo_post2.asp",true);
 xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
 xmlhttp.send("fname=Henry&lname=Ford");
 }