簡體   English   中英

我如何將表單值傳遞給Servlet

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

我是編程的新手,請耐心等待。

我正在嘗試使用javascript從表單(在JSP中)獲取值,並對servlet進行發布請求。 我的表單有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,這將是您的data元素。

在您的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