Добавить параметр в запрос к роуту
Этот код рабочий (ниже). При запросе http://localhost:8080/api/users/user?id=1 возвращает пользователя с id = 1. Чтобы получить список пользователей http://localhost:8080/api/users
Вопрос в следующем, как реализовать контроллер, чтобы получать пользователей по id следующим запросом? http://localhost:8080/api/users?id=1
Если я не указываю роут @GetMapping("/user") то берется соотвественно основной - @RequestMapping("/api/users")
При сборке возникает ошибка 
controller
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
@PostMapping
public ResponseEntity registration(@RequestBody UsersEntity user) {
try {
userService.registration(user);
return ResponseEntity.ok("Пользователь успешно создан");
} catch (UserAlreadyExistException e) {
return ResponseEntity.badRequest().body(e.getMessage());
}
catch (Exception e) {
return ResponseEntity.badRequest().body("Произошла ошибка");
}
}
@GetMapping
public ResponseEntity getUsers() {
try {
return ResponseEntity.ok(userService.getAll());
} catch (Exception e) {
return ResponseEntity.badRequest().body("Произошла ошибка");
}
}
@GetMapping("/user")
public ResponseEntity getOneUser(@RequestParam Long id) {
try {
return ResponseEntity.ok(userService.getOne(id));
} catch (UserNotFoundException e) {
return ResponseEntity.badRequest().body(e.getMessage());
}
catch (Exception e) {
return ResponseEntity.badRequest().body("Произошла ошибка");
}
}
}
service
@Service
public class UserService {
@Autowired
private UserRepo userRepo;
public UsersEntity registration(UsersEntity user) throws UserAlreadyExistException {
if(userRepo.findByUsername(user.getUsername()) != null) {
throw new UserAlreadyExistException("Пользователь с таким email адресом существует"); // проверка на пользователя в базе данных
}
return userRepo.save(user);
}
public Iterable <UsersEntity> getAll() {
return userRepo.findAll();
}
public UsersEntity getOne(Long id) throws UserNotFoundException {
UsersEntity user = userRepo.findById(id).get();
if (user == null) {
throw new UserNotFoundException("Пользователь не найден");
}
return user;
}
}
Ответы (1 шт):
Автор решения: Сергей
→ Ссылка
Наверное наиболее удобное решение в данном случае реализовать следующим образом:
пример запроса: http://localhost:8080/api/users/2
@GetMapping("/{id}")
public ResponseEntity getOneUser(@PathVariable Long id) {
try {
return ResponseEntity.ok(userService.getOne(id));
} catch (UserNotFoundException e) {
return ResponseEntity.badRequest().body(e.getMessage());
}
catch (Exception e) {
return ResponseEntity.badRequest().body("Произошла ошибка");
}
}
}