Springboot常用方法参数注解及示例

Springboot常用方法参数注解及示例

一、@RequestParam: 从URL查询参数中提取数据。

@GetMapping("/greet")
public ResponseEntity<String> greet(@RequestParam String name) {
    return ResponseEntity.ok("Hello, " + name + "!");
}

二、@PathVariable: 从URL路径中提取数据。

@GetMapping("/users/{userId}")
public ResponseEntity<User> getUserById(@PathVariable Long userId) {
    User user = userService.getUserById(userId);
    return ResponseEntity.ok(user);
}

三、@RequestBody: 从请求体中提取数据,并映射到对象。

@PostMapping("/create-user")
public ResponseEntity<String> createUser(@RequestBody User user) {
    userService.createUser(user);
    return ResponseEntity.ok("User created successfully");
}

四、@RequestHeader: 从请求头中提取数据。

@GetMapping("/user-agent")
public ResponseEntity<String> getUserAgent(@RequestHeader("User-Agent") String userAgent) {
    return ResponseEntity.ok("User Agent: " + userAgent);
}

五、@Validated / @Valid: 启用方法参数校验,确保参数满足校验规则。

@PostMapping("/register")
public ResponseEntity<String> registerUser(@Validated @RequestBody UserRegistrationDTO registrationDTO) {
    // 执行用户注册逻辑
    return ResponseEntity.ok("用户注册成功");
}

六、@ModelAttribute: 从请求参数或表单数据中提取数据,并映射到对象。

@PostMapping("/update-user")
public ResponseEntity<String> updateUser(@ModelAttribute UserUpdateDTO updateDTO) {
    userService.updateUser(updateDTO);
    return ResponseEntity.ok("User updated successfully");
}

七、@RequestPart: 从multipart/form-data类型的请求中提取数据。

@PostMapping("/upload")
    public ResponseEntity<String> uploadImage(@Validated @RequestPart ImageUploadDTO uploadDTO) {
        MultipartFile imageFile = uploadDTO.getImage();
        String description = uploadDTO.getDescription();
        return ResponseEntity.ok("图片上传成功:" + description);
    }