Java 如何将表单值传递给servlet

Java 如何将表单值传递给servlet,java,javascript,ajax,jsp,servlets,Java,Javascript,Ajax,Jsp,Servlets,我对编程相当陌生,所以请容忍我 我试图使用javascript从表单(JSP中)获取值,并向servlet发出post请求。我的表单有6个值,我使用javascript获取这些值 var value 1 = document.getElementByID(" value of a element in the form).value var value 2 = document.getElementByID(" value of a element in the form).valu

我对编程相当陌生,所以请容忍我

我试图使用javascript从表单(JSP中)获取值,并向servlet发出post请求。我的表单有6个值,我使用javascript获取这些值

var value 1 =    document.getElementByID(" value of a element in the form).value
var value 2 =    document.getElementByID(" value of a element in the form).value
etc

我的问题是,我正在使用javascript Ajax调用使用POST请求。如何将所有这些不同的值组合成一个元素,然后使用servlet中的POJO setter方法读取并分配给POJO。我不能使用JSON,因为我的项目不能使用外部库,如Jersey。任何指向这一点的提示都将不胜感激。

有更优雅的方法可以做到这一点,但这是最基本的。您需要将javascript变量组合到标准的帖子正文中

var postData = 'field1=' + value1;
postData += '&field2=' + value2;
postData += '&field3=' + value3;
/*  You're concatenating the field names with equals signs 
 *  and the corresponding values, with each key-value pair separated by an ampersand.
 */
如果您使用的是原始XMLHttpRequest工具,那么这个变量将是
send
方法的参数。如果使用jQuery,这将是您的
数据
元素

在servlet中,从容器提供的HttpServletRequest对象获取值

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    MyObject pojo = new MyObject();
    pojo.setField1(request.getParameter("field1"));
    pojo.setField2(request.getParameter("field2"));
    pojo.setField3(request.getParameter("field3"));
    /*  Now your object contains the data from the ajax post.
     *  This assumes that all the fields of your Java class are Strings.
     *  If they aren't, you'll need to convert what you pass to the setter.
     */ 
}

感谢您的回复,我应该向requests中的datatype字段添加什么,这取决于您从servlet发送的响应类型。默认情况下,它是text/html,因此如果要返回xml、json、纯文本等,则只需指定数据类型。