JSON HttpServletRequest / HttpServletResponse

时间:2016-04-19 15:19:09

标签: javascript java json ajax

我对Java世界很陌生,并且在查找如何将变量JSON字符串(见下文)存储在变量中然后将其转换为JSON对象时遇到了一些麻烦,然后可以将其转换为#welcometext div。

我已经查看了很多回复,但没有任何工作。如果有人能给我一些帮助,我将非常感激!

ActionServlet.java doPost:

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//    String body = request.getReader().lines().reduce("", (acc, actual) -> acc + actual);
    String body = request.getParameter("data");
    System.out.println("Body is: " + body);

    JsonReader jsonReader = Json.createReader(new StringReader(body));
    JsonObject obj = jsonReader.readObject();
    System.out.println("obj is: " + obj);
    jsonReader.close();

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");

  }
}

的index.html:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Ajax Demo</title>
<script src="http://code.jquery.com/jquery-latest.js">   
</script>
<script>
  $(document).ready(function() {

    var form2object = function(form) {
      var data = {};
      $('form').find('input').each(function(index, element) {
        var type = $(this).attr('type');
        if ($(this).attr('name') && type !== 'submit' && type !== 'hidden') {
          data[$(this).attr('name')] = $(this).val();
        }
      });

      return data;
    };

    var wrap = function wrap(root, formData) {
      var wrapper = {};
      wrapper[root] = formData;
      return wrapper;
    };

    var callback = function callback(error, data) {
      if (error) {
        console.error(error);
        $('#welcometext').val('status: ' + error.status + ', error: ' + error.error);
        return;
      }

      $('#welcometext').val(JSON.stringify(data, null, 4));
    };


    $('#submit').on('click', function(e) {
      e.preventDefault();
      console.log(form2object(this));
      var credentials = wrap('credentials', form2object(this));
      console.log("credentials is: " + credentials);

      $.ajax({
        method: 'POST',
        url: 'JQueryAjaxDemo/ActionServlet',
        contentType: 'application/json',
        data: JSON.stringify(credentials, null, 4),
        dataType: 'json'
      }, callback);

    }); //end of on click function
  }); //end of doc ready
</script>
</head>
<body>
  <form id="form1">
    <h1>AJAX Demo using Jquery and Servlets</h1>

    Enter your Info:
    <br>
     <input name ="name" type="text" id="user" placeholder="name" />
     <br>
     <input name="age" type="text" id="age" placeholder="age"/>
     <br>
     <input type="button" id="submit" value="Ajax Submit"/>
    <div id="welcometext">
    </div>
  </form>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

您调用request.getParameter("data")获取URL中查询字符串的值。但是,您的javascript似乎根本没有向查询字符串发送请求。在我看来,javascript发送一个{"credentials": {...}}正文的POST请求。使用request.getInputStream()来阅读请求正文。