无法接收json到servlet post方法

时间:2017-12-05 09:30:13

标签: json servlets jquery-ajaxq

我试图将json数据发送到我的serlvlet。但当我尝试接收时,我得到了null。以下是我的代码。我哪里错了?我不明白。

的index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function test(){
    var dataa={
             "otp":"abc",
             "email":"abcabc"
        };
    $.ajax({ 
       url: "AbcTest",
       type: 'POST',
       dataType: 'json',
       data:
       {    dataa: JSON.stringify(dataa)
          },
       contentType:'application/json; charset=utf-8',
       success: function (response) {
           console.log(JSON.stringify(response));
       },
       error: function(xhr, resp, text) {
          alert("error");
          console.log(xhr, resp, text);
       } 
  });
}
</script>
</head>
<body>
<button onclick="test();">Submit</button>
</body>
</html>

AbcTest Servlet

package org.abc.ussd;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/AbcTest")
public class AbcTest extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public AbcTest() {
        super();
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println(request.getParameter("dataa"));
    }
}

我在dataa的{​​{1}}中获取空格。如何从jsp页面接收json数据到此servlet。

1 个答案:

答案 0 :(得分:1)

当我将内容类型更改为

时,我能够解决此问题
contentType: "application/x-www-form-urlencoded; charset=UTF-8;",

我在控制台

中获得了以下输出

enter image description here