简体   繁体   中英

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 . My form has 6 values and I get the values in javascript using

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 . 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 . I cannot use a JSON because my project cannot use an external library such as 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.

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. If using jQuery, this would be your data element.

In your servlet, you get the values from the HttpServletRequest object provided by the container.

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.
     */ 
}

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