POST方法作为GET发送到servlet

时间:2017-06-05 08:33:45

标签: jquery ajax servlets

我正在尝试使用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>

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

enter image description here

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

  

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

我的代码出了什么问题?我尝试了很多解决方案但没有任何效果。

我的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();
    }
}

}

2 个答案:

答案 0 :(得分: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);
    }
  });

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

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

以上formData保存json格式的输入值,有利于解析。

希望这有帮助!!!

答案 1 :(得分:0)

由于content-type,当您使用post方法发送数据时,您必须使用x-www-form-urlencoded(默认情况下为$.ajax),例如

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

而不是

contentType: "application/json",

还使用dataType:'json'来获取JSON响应。详细了解$.ajax()

上的contentTypedataType