如何从JSP页面的jquery AJAX请求转发JSON数据到servlet页面?

时间:2014-08-07 08:27:06

标签: jquery ajax json servlets

我没有收到我从JSP页面上的AJAX请求发送的JSON数据。当我尝试打印存储request.getParameterValues(“json []”)的数组时,我得到空指针异常。

我的代码如下:

HTML:

<form name="form1" method="post" action="dailyWBSupload">
 <button class="btn btn-default btn-rect" type="submit" id="taskstodb">Forward</button>
</form>

jquery / AJAX脚本:

   var form = $('#form1');
        form.submit(function() {
            var json = [1, 2, 3, 4];
            jQuery.ajax({
                type: "POST",
                url: "dailyWBSupload",
                dataType: 'json',
                data: {json: json},
                contentType: 'application/json',
                mimeType: 'application/json',
                success: function(data) {
                    alert('YES!');
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    alert(jqXHR + " - " + textStatus + " - " + errorThrown);
                }
            });
        });

的web.xml:

 <servlet>
    <servlet-name>dailyWBSupload</servlet-name>
    <servlet-class>serves.dailyWBSupload</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>dailyWBSupload</servlet-name>
    <url-pattern>/dailyWBSupload</url-pattern>
</servlet-mapping>

我的Servlet(dailyWBSupload.java):

public class dailyWBSupload extends HttpServlet {

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //response.setContentType("text/html;charset=UTF-8");

    String[] myJsonData = request.getParameterValues("json[]");
    System.err.println("O/P: " + myJsonData[0]);


}

}

2 个答案:

答案 0 :(得分:0)

从ajax调用中删除这两行:

contentType: 'application/json',
mimeType: 'application/json',

或将内容类型更改为:

contentType: 'application/x-www-form-urlencoded;'

更改后的ajax调用:

   $.ajax({
           type: "POST",
           url: "AnotherServlet",
           dataType: 'json',
           data: {json: json},         
           success: function(data) {
               alert('YES!');
           },
           error: function(jqXHR, textStatus, errorThrown) {
               alert(jqXHR + " - " + textStatus + " - " + errorThrown);
           }
       });

有关详情see this answer

答案 1 :(得分:0)

事实证明,上面的方法是错误的,因为即使在对它进行多次调整之后,我也没有一次工作。 所以我改变了我的方法,我使用了AJAX.updater()方法来做同样的事情。

使用Javascript:

 $("#taskstodb").click(function() {
                var table = $('#WBStable').tableToJSON(); // Convert the table into a javascript object
                alert(JSON.stringify(table));
                var json = JSON.stringify(table);
                new Ajax.Request('dailyWBSupload', {
                    method: 'get',
                    parameters: {json: json}
                });
            });

的Servlet

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    String tabledata = request.getParameter("json");
    System.err.println(tabledata);
    final String JSON_DATA
            = "{" + "  \"geodata\": " + tabledata + "}";
    System.err.println(JSON_DATA);
    final JSONObject obj;
    String taskname;
    String noOfhours;
    try {
        obj = new JSONObject(JSON_DATA);
        final JSONArray geodata = obj.getJSONArray("geodata");
        final int n = geodata.length();
        for (int i = 0; i < n; ++i) {
            final JSONObject taskinfo = geodata.getJSONObject(i);
            taskname = taskinfo.getString("Task");
            noOfhours = taskinfo.getString("No. of Hours");

        }
    } catch (JSONException ex) {
        ex.printStackTrace();
    }

}