|
| 1 | +package org.baeldung.web.controller; |
| 2 | + |
| 3 | +import java.util.HashMap; |
| 4 | +import java.util.List; |
| 5 | +import java.util.Map; |
| 6 | +import java.util.regex.Matcher; |
| 7 | +import java.util.regex.Pattern; |
| 8 | + |
| 9 | +import org.baeldung.persistence.model.User; |
| 10 | +import org.baeldung.persistence.service.impl.UserService; |
| 11 | +import org.springframework.beans.factory.annotation.Autowired; |
| 12 | +import org.springframework.stereotype.Controller; |
| 13 | +import org.springframework.web.bind.annotation.RequestMapping; |
| 14 | +import org.springframework.web.bind.annotation.RequestMethod; |
| 15 | +import org.springframework.web.bind.annotation.RequestParam; |
| 16 | +import org.springframework.web.bind.annotation.ResponseBody; |
| 17 | + |
| 18 | +@Controller |
| 19 | +public class UserController { |
| 20 | + |
| 21 | + @Autowired |
| 22 | + private UserService service; |
| 23 | + |
| 24 | + public UserController() { |
| 25 | + super(); |
| 26 | + } |
| 27 | + |
| 28 | + @RequestMapping(method = RequestMethod.GET, value = "/users") |
| 29 | + @ResponseBody |
| 30 | + public List<User> findAll(@RequestParam(value = "search", required = false) final String search) { |
| 31 | + final Map<String, Object> params = new HashMap<String, Object>(); |
| 32 | + |
| 33 | + if (search != null) { |
| 34 | + final Pattern pattern = Pattern.compile("(\\w+?):(\\w+?),"); |
| 35 | + final Matcher matcher = pattern.matcher(search + ","); |
| 36 | + while (matcher.find()) { |
| 37 | + params.put(matcher.group(1), matcher.group(2)); |
| 38 | + } |
| 39 | + } |
| 40 | + return service.searchUser(params); |
| 41 | + } |
| 42 | + |
| 43 | + @RequestMapping(method = RequestMethod.GET, value = "/users/spec") |
| 44 | + @ResponseBody |
| 45 | + public List<User> findAllBySpecification(@RequestParam(value = "search", required = false) final String search) { |
| 46 | + final Map<String, Object> params = new HashMap<String, Object>(); |
| 47 | + |
| 48 | + if (search != null) { |
| 49 | + final Pattern pattern = Pattern.compile("(\\w+?):(\\w+?),"); |
| 50 | + final Matcher matcher = pattern.matcher(search + ","); |
| 51 | + while (matcher.find()) { |
| 52 | + params.put(matcher.group(1), matcher.group(2)); |
| 53 | + } |
| 54 | + } |
| 55 | + return service.searchBySpecification(params); |
| 56 | + } |
| 57 | + |
| 58 | + @RequestMapping(method = RequestMethod.GET, value = "/users/new") |
| 59 | + @ResponseBody |
| 60 | + public long addUser(@RequestParam("first") final String first, @RequestParam("last") final String last, @RequestParam("age") final int age) { |
| 61 | + final User user = new User(); |
| 62 | + user.setFirstName(first); |
| 63 | + user.setLastName(last); |
| 64 | + user.setEmail("john@doe.com"); |
| 65 | + user.setAge(age); |
| 66 | + service.saveUser(user); |
| 67 | + return user.getId(); |
| 68 | + } |
| 69 | +} |
0 commit comments