0

私はプログラミングにかなり慣れていないので、ご容赦ください。

javascript を使用して (JSP 内の) フォームから値を取得し、サーブレットにポスト リクエストを実行しようとしています。私のフォームには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 call を使用して POST リクエストを使用していることです。これらの異なる値をすべて 1 つの要素に結合し、それを読み取って servlet の POJO の setter メソッドを使用して POJO に割り当てるにはどうすればよいでしょうか。プロジェクトで Jersey などの外部ライブラリを使用できないため、JSON を使用できません。これに対する任意のポインタをいただければ幸いです。

4

1 に答える 1

0

これを行うにはもっと洗練された方法がありますが、これが最も基本的な方法です。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要素になります。

サーブレットでは、コンテナーによって提供される 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.
     */ 
}
于 2013-11-09T23:18:24.673 に答える