-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProductController.java
More file actions
26 lines (23 loc) · 921 Bytes
/
ProductController.java
File metadata and controls
26 lines (23 loc) · 921 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.example.RestExample_validate;
@RestController
@RequestMapping("/api/products")
public class ProductController {
private final List<Product> products = new ArrayList<>();
@PostMapping
public ResponseEntity<?> addProduct(@Valid @RequestBody Product product, BindingResult result) {
List<String> displayErrors = new ArrayList<String>();
if (result.hasErrors()) {
List<FieldError> errors = result.getFieldErrors();
for(FieldError err:errors) {
displayErrors.add(err.getField() + ": " + err.getDefaultMessage());
System.out.println(displayErrors);
}
return ResponseEntity.badRequest().body(displayErrors);
}
products.add(product);
return ResponseEntity.status(HttpStatus.CREATED).body(product);
}
@GetMapping
public List<Product> getProduct(){
return products;
}