2013-11-09 231 views
0

我對編程相當陌生,請耐心等待。如何將表單值傳遞給servlet

我想從使用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 

我的問題是我使用POST請求使用JavaScript Ajax調用。如何將所有這些不同的值組合到一個單獨的元素中,然後我可以使用POJO的setter方法在servlet中讀取並分配給POJO。我無法使用JSON,因爲我的項目無法使用澤西島等外部庫。任何指針,這將不勝感激。

回答

0

有更優雅的方式來做到這一點,但這是最基本的。你會想要將你的javascript變量組合到一個標準的post主體中。

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

謝謝您的答覆,我該怎麼添加到數據類型字段以取決於響應你從servlet發送類型的請求 – user1801279

+0

。默認情況下,它是text/html,因此如果您發送的是xml,json,純文本等,則只需指定dataType。 – Tap