简体   繁体   English

我如何将表单值传递给Servlet

[英]How would I pass a form value to a servlet

I am fairly new to programming so please bear with me . 我是编程的新手,请耐心等待。

I am trying to get values from a form ( in a JSP ) using javascript and do a post request to a servlet . 我正在尝试使用javascript从表单(在JSP中)获取值,并对servlet进行发布请求。 My form has 6 values and I get the values in javascript using 我的表单有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

my question is I am using a POST request using the javascript Ajax call . 我的问题是我正在使用javascript Ajax调用使用POST请求。 How do I combine all these disparate values into a single element which I could then read and assign to a POJO using the POJO'S setter methods in the servlet . 如何将所有这些不同的值组合到一个元素中,然后可以使用servlet中的POJO的setter方法读取并分配给POJO。 I cannot use a JSON because my project cannot use an external library such as Jersey. 我无法使用JSON,因为我的项目无法使用外部库(例如Jersey)。 Any pointers to this would be appreciated . 任何对此的指点将不胜感激。

There are more elegant ways to do this, but this is the most basic. 有更优雅的方法可以做到这一点,但这是最基本的。 You'll want to combine your javascript variables into a standard post body. 您需要将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.
 */

If you're using the raw XMLHttpRequest facilities, this variable would be the argument to the send method. 如果使用的是原始XMLHttpRequest工具,则此变量将作为send方法的参数。 If using jQuery, this would be your data element. 如果使用jQuery,这将是您的data元素。

In your servlet, you get the values from the HttpServletRequest object provided by the container. 在您的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.
     */ 
}

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

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