skip to Main Content

I was trying a code which was a bit more complex and was testing things when everything I put into spring boot came out as null in the other end

Therefore I made the program simpler until I thought I knew it should work, but it still didn’t.
I am using springboot severeal places in my program, and it works there. Why doesn’t it work here?

@PostMapping("/Test")
public void Test(String number)
{
  System.out.println("Number " + number);
}
$.post("/Test", "1")

This is what my console prints:

Number null

2

Answers


  1. Assuming this will be your java code.

    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class TestController {
    
        @PostMapping("/Test")
        public void test(@RequestBody String number) {
            System.out.println("Number " + number);
        }
    }
    

    you need to pass it like below code.

    // Make a POST request using jQuery's $.post method
    $.post('/Test', { number: '123' })
        .done(function(data) {
            console.log('Success:', data); // Handle the success response
        })
        .fail(function(xhr, status, error) {
            console.error('Error:', error); // Handle any errors
        });
    

    you can use ajax also.

    // Make an AJAX POST request using jQuery
    $.ajax({
        url: '/Test',
        type: 'POST',
        data: { number: '123' }, // Pass the 'number' parameter
        success: function(data) {
            console.log('Success:', data); // Handle the success response
        },
        error: function(xhr, status, error) {
            console.error('Error:', error); // Handle any errors
        }
    });
    
    Login or Signup to reply.
  2. For Post you have to use @RequestBody

    try

    @PostMapping("/Test")
    public void Test( @RequestBody String number)
    {
      System.out.println("Number " + number);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search