Servlet request.getParameter返回null

时间:2015-01-08 04:46:42

标签: java javascript jquery ajax servlets

在网页上,我使用JQuery向我的servlet发送Ajax调用。

function sendAjax() {
            $.ajax({
                url: "/AddOrUpdateServlet",
                type: 'POST',   
                dataType: 'json',
                data: {"name": "hello world"},
                contentType: 'application/json',
                mimeType: 'application/json',

                success: function (data) {   

                },
                error:function(data,status,er) {
                    alert("error: "+data+" status: "+status+" er:"+er);
                }
            });         
        }   

在AddOrUpdateServlet的doPost中,我有以下代码:

protected void doPost(HttpServletRequest request, 
        HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub 
    String name = request.getParameter("name"); 
    if (name == null) 
        System.out.println("null"); 

    /*
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(new Integer(1).toString());
    response.getWriter().close();
    */

}

我可以看到,当控制台打印出" null"时,servlet已成功发送和接收参数。但是为什么servlet无法获得" name" PARAM?

1 个答案:

答案 0 :(得分:0)

因为您已通过"name"中的request body of POST参数,所以JSON类型更新。

只需提出GET请求并删除以下行

即可
`contentType: 'application/json',mimeType: 'application/json',

编辑: - 在servlet中编写下面的代码行,你必须使用JSON库来解析servlet中的数据(GSON or Jackson)    请参阅: - Stack overflow answer

StringBuffer jb = new StringBuffer();
  String line = null;
  try {
    BufferedReader reader = request.getReader();
    while ((line = reader.readLine()) != null)
      jb.append(line);
  } catch (Exception e) { /*report an error*/ }

  try {
    JSONObject jsonObject = JSONObject.fromObject(jb.toString());
  } catch (ParseException e) {
    // crash and burn
    throw new IOException("Error parsing JSON request string");
  }