-1

I have made a crud ajax rest application using spring framework. The problem is: When i am sending post from client to server, i am getting object filled with nulls, from client side i have status 200. Here is my code:

Product class

public class Product {//getters,setters and toString() generated with Eclipse
     private Integer id;
     private String name;
     private String description;
     private String createdDate;
     private Integer placeStorage;
     private Boolean reserved;

Rest controller

@RestController
public class ProductRestController {
    
    @Autowired
    private ProductServiceImpl productService;
    
    @PostMapping(value = "/getRecord")
    public void addProduct(Product product) {
        System.out.println(product);
    }
    
}

AJAX function

function sendRecord(data){
        $.ajax({
            type : 'POST',
            url : '/getRecord',
            contentType : "application/json",
            cache : false,
            dataType: 'json',
            processData:false,
            data: data,
            dataType:'json',
            success : function(data) {
                update_table();
            }
        });
    }

Data that i am posting

Data that i am posting

Data that i am getting

Data that i am getting

john2994
  • 393
  • 1
  • 3
  • 15

2 Answers2

2

You don't tell Spring where to get your product from. You miss an annotation.

@RestController
public class ProductRestController {
    
    @Autowired
    private ProductServiceImpl productService;
    
    @PostMapping(value = "/getRecord")
    public void addProduct(@RequestBody Product product) {
        System.out.println(product);
    }
    
}

You should also think about rename /getRecord since you don't get anything but send something. :)

Milgo
  • 2,617
  • 4
  • 22
  • 37
1

Take a look into @RequestBody annotation https://www.baeldung.com/spring-request-response-body.

@PostMapping(value = "/getRecord")
    public void addProduct(@RequestBody Product product) {
        System.out.println(product);
    }

It will automatically map request body data into your Product object. If you got time also take a look into @RequestParam and @PathVariable, they are all for data getting and works in differents ways for different goals.

William Rizzi
  • 413
  • 3
  • 8