|
| 1 | +package com.baeldung.springmvcforms.controller; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Collections; |
| 5 | +import java.util.List; |
| 6 | + |
| 7 | +import javax.validation.Valid; |
| 8 | +import org.springframework.http.HttpStatus; |
| 9 | +import org.springframework.http.MediaType; |
| 10 | +import org.springframework.http.ResponseEntity; |
| 11 | +import org.springframework.stereotype.Controller; |
| 12 | +import org.springframework.ui.Model; |
| 13 | +import org.springframework.validation.BindingResult; |
| 14 | +import org.springframework.validation.ObjectError; |
| 15 | +import org.springframework.web.bind.annotation.GetMapping; |
| 16 | +import org.springframework.web.bind.annotation.PostMapping; |
| 17 | +import org.springframework.web.bind.annotation.ResponseBody; |
| 18 | + |
| 19 | +import com.baeldung.springmvcforms.domain.User; |
| 20 | + |
| 21 | +@Controller |
| 22 | +public class UserController { |
| 23 | + |
| 24 | + List<User> users = new ArrayList<User>() { |
| 25 | + { |
| 26 | + add(new User("ana@yahoo.com", "pass", "Ana", 20)); |
| 27 | + add(new User("bob@yahoo.com", "pass", "Bob", 30)); |
| 28 | + add(new User("john@yahoo.com", "pass", "John", 40)); |
| 29 | + add(new User("mary@yahoo.com", "pass", "Mary", 30)); |
| 30 | + } |
| 31 | + }; |
| 32 | + |
| 33 | + @GetMapping("/userPage") |
| 34 | + public String getUserProfilePage() { |
| 35 | + return "user"; |
| 36 | + } |
| 37 | + |
| 38 | + @PostMapping(value = "/user", produces = MediaType.APPLICATION_JSON_VALUE) |
| 39 | + @ResponseBody |
| 40 | + public ResponseEntity<Object> saveUser(@Valid User user, BindingResult result, Model model) { |
| 41 | + if (result.hasErrors()) { |
| 42 | + List<String> errors = new ArrayList<>(); |
| 43 | + result.getAllErrors().forEach(item->{ |
| 44 | + errors.add(item.getDefaultMessage()); |
| 45 | + }); |
| 46 | + return new ResponseEntity<>(errors, HttpStatus.OK); |
| 47 | + } else { |
| 48 | + if (users.stream().anyMatch(it -> user.getEmail().equals(it.getEmail()))) { |
| 49 | + return new ResponseEntity<>(Collections.singletonList("Email already exists!"), HttpStatus.CONFLICT); |
| 50 | + } else { |
| 51 | + users.add(user); |
| 52 | + return new ResponseEntity<>(HttpStatus.CREATED); |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + @GetMapping(value = "/users", produces = MediaType.APPLICATION_JSON_VALUE) |
| 58 | + @ResponseBody |
| 59 | + public List<User> getUsers() { |
| 60 | + return users; |
| 61 | + } |
| 62 | + |
| 63 | +} |
0 commit comments