简体   繁体   English

使用Spring和Ajax从Post方法接收Rest控制器中的参数

[英]Receive parameters in Rest controller from Post method using Spring and Ajax

I'm trying to send two parameters using AJAX to my Spring REST controller using the POST method. 我正在尝试使用POST方法使用AJAX将两个参数发送到我的Spring REST控制器。 However those parameters are appearing as null in my controller. 但是这些参数在我的控制器中显示为null Please find the code and let me know if I'm missing anything. 请找到代码,如果我遗漏任何东西,请告诉我。

var formData = {
  txToClose: '1234,5678,98549',
  sno:  '0195'
};

$.ajax({
  type: 'post',
  url: url,
  async: false,  
  data: JSON.stringify(formData),
  contentType: "application/json",
  dataType: "json",      
  success: function(result, status, xhr) {
    console.log(result);
  }                           
});
@PostMapping("/txToClose")  
public ResultDto txToClose(HttpServletRequest request, HttpServletResponse response) throws BBException
{
  logger.info("Called txToClose controller");
  ResultDto resultDto = new ResultDto();

  String txToClose = request.getParameter("txToClose");
  String sno = request.getParameter("sno");

  logger.info("Transactions to close :" + txToClose + ", Serial Num :" + sno);
}

create class like this : 创建这样的类:

    class Myclass{
          private String  txToClose;
             private String    sno; 
 // getters setters
    }

and in your method like this : 并在您的方法是这样的:

@PostMapping("/txToClose")  
public ResultDto txToClose(@RequestBody Myclass class ) throws BBException
{
   // your logic
}

I think the part which is not working in your code is the request.getParameter() as it would not be able to identify the paramters and values in case of json data. 我认为在您的代码中不起作用的部分是request.getParameter(),因为在json数据的情况下它将无法识别参数和值。 Instead use something like this: 而是使用类似以下的内容:

StringBuilder sb = new StringBuilder();
BufferedReader reader = request.getReader();
try {
      String line;
      while ((line = reader.readLine()) != null) {
          sb.append(line).append('\n');
      }
 } 
 finally {
        reader.close();
 }
 System.out.println(sb.toString());

Use the above logic in your controller to process the json request.Please refer this link for further ideas to process json when taken as HttpServeletRequest. 在您的控制器中使用上述逻辑来处理json请求。如果将其作为HttpServeletRequest来处理json,请参考此链接以获取进一步的想法。

Solved by using 通过使用解决

public ResultDto txToClose(HttpServletRequest request, HttpServletResponse response,@RequestBody ObjectNode json) throws BBException { 
    logger.info("Called txToClosecontroller"); 
    ResultDto result = new ResultDto(); 
    String txToClose= json.get("txToClose").asText(); 
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM