【问题标题】:POST method is sent as GET to the servlet [duplicate]POST 方法作为 GET 发送到 servlet [重复]
【发布时间】:2017-06-05 08:33:45
【问题描述】:

我正在尝试使用 POST 命令向我的 servlet 填充表格,但我的网页没有发送 POST 请求,而是向 servlet 发送了 GET 请求。这是我的

$(document).ready(function() {
  $.get("league", function(responseJson) {
    if (responseJson != null) {
      $("#tableleague").find("tr:gt(0)").remove();
      var table1 = $("#tableleague");
      $.each(responseJson, function(key, value) {
        var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>");
        rowNew.children().eq(0).text(value['teams']);
        rowNew.children().eq(1).text(value['playedgames']);
        rowNew.children().eq(2).text(value['wongames']);
        rowNew.children().eq(3).text(value['tiegames']);
        rowNew.children().eq(4).text(value['lostgames']);
        rowNew.children().eq(5).text(value['scoredgoal']);
        rowNew.children().eq(6).text(value['scoredgoal']);
        rowNew.children().eq(7).text(value['scoredgoal']);
        rowNew.appendTo(table1);
      });
    }
  });
});

function addData() {
  var t1 = $("#firstteam").val();
  var t2 = $("#secondteam").val();
  var s1 = $("#score1").val();
  var s2 = $("#score2").val();
  $("#firstteam").val('');
  $("#secondteam").val('');
  $("#score1").val('');
  $("#score2").val('');
  var data = {
    firstteam: "t1",
    secondteam: "t2",
    score1: "s1",
    score2: "s2"
  }

  $.ajax({
    type: "POST",
    url: "league",
    data: JSON.stringify(data),
    contentType: "application/x-www-form-urlencoded",
    dataType:'json',
    success: function(data, textStatus, jqXHR) {
      if (data.success) {
        $("#error").html("<div><b>Success!</b></div>" + data);
      } else {
        $("#error").html("<div><b>Information is Invalid!</b></div>" + data);
      }
    },
    error: function(jqXHR, textStatus, errorThrown) {
      console.log("Something really bad happened " + textStatus);
      $("#error").html(jqXHR.responseText);
    }
  });
}
<h1>League Table</h1>
<table cellspacing="0" id="tableleague" style="width:100%">
  <tr>
    <th scope="col">Teams</th>
    <th scope="col">Won</th>
    <th scope="col">Tie</th>
    <th scope="col">Lost</th>
    <th scope="col">Scored</th>
    <th scope="col">Received</th>
    <th scope="col">Points</th>
  </tr>
</table>

<form method="POST">
  <div class="form_group">
    <label for="FirstTeam">FirstTeam:</label>
    <input type="text" class="form_control" id="firstteam">
  </div>
  <div class="form_group">
    <label for="Score1">Score1:</label>
    <input type="text" class="form_control" id="score1">
  </div>
  <div class="form_group">
    <label for="Score2">Score2:</label>
    <input type="text" class="form_control" id="score2">
  </div>
  <div class="form_group">
    <label for="SecondTeam">SecondTeam:</label>
    <input type="text" class="form_control" id="secondteam">
  </div>
  <div class="form_group">
    <button type="submit" class="addbutton" id="addbut" onclick="addData();">Add match</button>
  </div>
</form>

<div id="error"></div>

这是我在按下“添加匹配”按钮后立即在调试器中看到的内容:

我在控制台收到的错误是这个:

POST http://localhost:8080/league/league500(内部服务器错误)

我的代码做错了什么?我尝试了很多解决方案,但都没有奏效。

我的 servlet 代码:

@WebServlet("/league/*")
public class PopulateTable extends HttpServlet {
private static final long serialVersionUID = 1L;

public PopulateTable()
{

}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    try
    {
        ArrayList<League> league = new ArrayList<League>();
        league= Controller.getAllController();
        Gson gson = new Gson();
        JsonElement element = gson.toJsonTree(league, new TypeToken<List<League>>() {}.getType());

        JsonArray jsonArray = element.getAsJsonArray();
        response.setContentType("application/json");
        response.getWriter().print(jsonArray);
    }
    catch (SQLException ex)
    {
        ex.printStackTrace();
    }
}


@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    try {
        PrintWriter out = response.getWriter();
        JsonObject data = new Gson().fromJson(request.getReader(), JsonObject.class);

        int s1 = Integer.parseInt(data.get("score1").getAsString());
        int s2 = Integer.parseInt(data.get("score2").getAsString());

        String t1 = data.get("firstteam").getAsString();;
        String t2 = data.get("secondteam").getAsString();;
        int ok = Controller.update(t1, t2, s1, s2);
        JsonObject myObj = new JsonObject();

        if(ok ==  1)
        {
            myObj.addProperty("success", true);
        }
        else {
            myObj.addProperty("success", false);
        }
        out.println(myObj.toString());

        out.close();

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

}

【问题讨论】:

  • instead of sending a POST request, my webpage sends a GET request 你正在使用$.get()...?
  • 您检查过您的服务器错误日志吗? 500 Internal Server Error 表示您的 JSP 端有问题,可能无法保存/插入数据。您需要检查日志。
  • 我使用 .get 作为我的第一个函数,在我第一次加载页面时填充表格,但是当我按下添加匹配按钮时,我的页面应该发送一个 AJAX POST 请求,它不会不要这样做。
  • 更改按钮类型
  • 更改了按钮类型,我看到了一个全新的世界。看起来我的错误在 servlet 中,int s1 变量给了我一个 java.lang.NumberFormatException。

标签: jquery ajax servlets


【解决方案1】:

好吧,对您的addData() 函数进行了以下更改。 在$.ajax()函数内部,创建一个param对象来保存表单数据,可以像这样传递给servlet。

var param = 'formdata='+JSON.stringify(data);
$.ajax({
    type: "POST",
    url: "/league",
    data: param,
    dataType:'json',
    success: function(data, textStatus, jqXHR) {
      if (data.success) {
        $("#error").html("<div><b>Success!</b></div>" + data);
      } else {
        $("#error").html("<div><b>Information is Invalid!</b></div>" + data);
      }
    },
    error: function(jqXHR, textStatus, errorThrown) {
      console.log("Something really bad happened " + textStatus);
      $("#error").html(jqXHR.responseText);
    }
  });

您可以使用HttpServletRequest 对象在您的PopulateTable servlet 中访问此数据对象。你可以访问像

String formData = request.getParameter("formdata");

上面的formData保存了json格式的表单输入值,很适合解析。

希望对你有帮助!!!

【讨论】:

  • 如何解析字符串以从中获取 score1、score2、teamfirst 和 teamsecond?如果我的问题看起来很愚蠢,我是 servlet 的新手,非常抱歉。
  • 同理,需要使用gson/jackson或者一些json解析库。只是为了确定我的代码。你能在PopulateTable servlet 的doPost 方法中打印一个sysout 语句吗?应该是System.out.println(request.getParameter("formdata"));
  • 我在代码中放了一个 println,但在任何地方都看不到结果,不是在 Tomcat 控制台或 Chrome 控制台中。
  • 它应该打印在 Tomcat 控制台上,因为 print 是 java sysout 是 java 方法。 500 停止了吗?
  • 是的,幸运的是。我所要做的就是弄清楚如何拆分字符串以获得 score1、score2 和其他单独变量。但是,tomcat 控制台中仍然没有打印任何内容。
【解决方案2】:

因为content-type,当你使用post方法发送数据时,你必须使用x-www-form-urlencoded(这是$.ajax中的默认值)之类的,

contentType: "application/x-www-form-urlencoded"

而不是

contentType: "application/json",

也可以使用dataType:'json' 来获取 JSON 响应。在$.ajax() 上阅读有关contentTypedataType 的更多信息

【讨论】:

  • 那么我应该在我的 servlet 中创建另一个类吗?现在我有一个类,它使用 doGet 方法和 doPost 方法映射到联赛。
  • 我收到同样的错误。我将我的 Ajax 从联赛更改为联赛,我在我的 servlet 中创建了一个映射到联赛的新类,只有一个 doPost 方法,但没有修复任何问题。
  • 尝试使用 $.ajax 中的 url:'/league' 而不是 url:'league'
猜你喜欢
  • 1970-01-01
  • 2019-01-23
  • 2015-09-07
  • 1970-01-01
  • 1970-01-01
  • 2016-01-29
  • 1970-01-01
  • 1970-01-01
  • 2013-08-16
相关资源
最近更新 更多