如何在 Spring boot Controller 中接受 GET 参数并返回适当的对象

Sto*_*000 1 spring-mvc spring-data-jpa spring-boot spring-restcontroller spring-rest

我对 Spring Boot 非常陌生,我不知道该类@Controller。如果我在 Spring Boot 中找不到数据库中的特定对象,我应该传递什么?如果我将返回类型声明为Response Entity并发送 null User 对象,会更好吗?

//Get single user
@GetMapping("/users/{id}")
public User getUser(@PathVariable String id){
    try {
        Long i = Long.parseLong(id);
    } catch (NumberFormatException ex) {
        return ????    //Can't figure out what to return here. 
    }
    return userService.getUser(id);
}
Run Code Online (Sandbox Code Playgroud)

我希望消费者知道他们发送了无效的字符串。

2)此外,用户的变量id是类型LongLong那么我应该采用函数中的参数getUser还是采用字符串并解析它?Long如果在链接中发送字符串,则采取 a会使我的服务器崩溃。

Cep*_*pr0 5

这是我用于“通过 id 获取用户”请求的 REST 控制器的典型代码:

@RestController
@RequestMapping("/users") // 1
public class UserController {

    private final UserRepo userRepo;

    public UserController(UserRepo userRepo) {
        this.userRepo = userRepo;
    }

    @GetMapping("/{id}") // 2
    public ResponseEntity getById(@PathVariable("id") Long id) { // 3
        return userRepo.findById(id) // 4
                .map(UserResource::new) // 5
                .map(ResponseEntity::ok) // 6
                .orElse(ResponseEntity.notFound().build()); // 7
    }
}
Run Code Online (Sandbox Code Playgroud)

在哪里:

1 - 是该控制器处理的所有请求的公共起始路径

2 - GET 请求的路径变量模式 ( /users/{id})。

3 - 提供路径变量的名称,该名称与 中的参数相对应GetMapping。方法中参数的类型getById与ID的类型相对应User

4 - 我使用我的返回findById方法UserRepoOptional

5 - 这里我转换User为某种类型的 DTO - UserResource(这是可选步骤)

6 -如果找到则返回OK响应User

7 - 或Not Found否则返回响应。