【问题标题】:unable to receive json to servlet post method无法接收 json 到 servlet 发布方法
【发布时间】:2017-12-05 09:30:13
【问题描述】:

我试图将json 数据发送到我的servlet。但是当我尝试接收时,我得到了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"));
    }
}

我在dataaservlet 中得到空值。如何从 jsp 页面接收 json 数据到这个 servlet。

【问题讨论】:

  • 您是否尝试过调试(前端通过浏览器调试器、网络监视器、后端通过 IDE 调试器)来缩小问题范围?如果没有,请做并分享结论。
  • 好吧,在浏览器中,我在 chrome 中的开发人员工具控制台中没有错误。在 servlet 中,我打印的是空值。

标签: json servlets jquery-ajaxq


【解决方案1】:

当我将内容类型更改为时,我能够解决此问题

contentType: "application/x-www-form-urlencoded; charset=UTF-8;",

我在控制台中得到以下输出

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-13
    • 2014-08-12
    • 2018-01-20
    相关资源
    最近更新 更多