3

I'm trying to send two parameters using AJAX to my Spring REST controller using the POST method. However those parameters are appearing as null in my controller. 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);
}
Yakhoob
  • 559
  • 1
  • 12
  • 32

3 Answers3

0

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
}
hicham abdedaime
  • 346
  • 2
  • 15
0

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. 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.

Mohit
  • 608
  • 4
  • 19
  • Mohit.. I solved the issue. 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(); } – Yakhoob Oct 12 '17 at 09:35
  • You used an entity to take the request then right?? – Mohit Oct 12 '17 at 09:36
  • It could have been possible without the @RequestBody as well, do try my method once to see whether it works or not. Just for testing purpose, if you can. – Mohit Oct 12 '17 at 09:38
0

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(); 
} 
Yakhoob
  • 559
  • 1
  • 12
  • 32