Controller层常用的注解

53
0
0
2020-12-30
Controller层常用的注解

Controller层常用的注解

当开发Spring MVC应用程序时,Controller层常用的注解包括:

  1. @Controller:将类标记为Controller组件。

@Controller
public class MyController {
    // Controller方法
}
  1. @RestController:将类标记为RESTful风格的Controller组件。

@RestController
public class MyRestController {
    // RESTful风格的Controller方法
}
  1. @RequestMapping:将请求映射到处理方法,并可指定请求路径、方法和其他属性。

@Controller
@RequestMapping("/api")
public class MyController {
    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String hello() {
        return "Hello, World!";
    }
}
  1. @GetMapping:将GET请求映射到处理方法。

@Controller
@RequestMapping("/api")
public class MyController {
    @GetMapping("/hello")
    public String hello() {
        return "Hello, World!";
    }
}
  1. @PostMapping:将POST请求映射到处理方法。

@Controller
@RequestMapping("/api")
public class MyController {
    @PostMapping("/users")
    public ResponseEntity<User> createUser(@RequestBody User user) {
        // 创建用户逻辑
        return ResponseEntity.ok(user);
    }
}
  1. @PutMapping:将PUT请求映射到处理方法。

@Controller
@RequestMapping("/api")
public class MyController {
    @PutMapping("/users/{id}")
    public ResponseEntity<User> updateUser(@PathVariable("id") Long id, @RequestBody User user) {
        // 更新用户逻辑
        return ResponseEntity.ok(user);
    }
}
  1. @DeleteMapping:将DELETE请求映射到处理方法。

@Controller
@RequestMapping("/api")
public class MyController {
    @DeleteMapping("/users/{id}")
    public ResponseEntity<Void> deleteUser(@PathVariable("id") Long id) {
        // 删除用户逻辑
        return ResponseEntity.noContent().build();
    }
}
  1. @PathVariable:将URL路径中的变量绑定到处理方法的参数。

@Controller
@RequestMapping("/api")
public class MyController {
    @GetMapping("/users/{id}")
    public ResponseEntity<User> getUserById(@PathVariable("id") Long id) {
        // 根据ID获取用户逻辑
        return ResponseEntity.ok(user);
    }
}
  1. @RequestParam:获取请求中的查询参数,并将其绑定到处理方法的参数。

@Controller
@RequestMapping("/api")
public class MyController {
    @GetMapping("/users")
    public ResponseEntity<List<User>> getUsersByRole(@RequestParam("role") String role) {
        // 根据角色获取用户逻辑
        return ResponseEntity.ok(users);
    }
}
  1. @RequestBody:将请求的请求体内容绑定到处理方法的参数。

@Controller
@RequestMapping("/api")
public class MyController {
    @PostMapping("/users")
    public ResponseEntity<User> createUser(@RequestBody User user) {
        // 创建用户逻辑
        return ResponseEntity.ok(user);
    }
}

这些注解提供了丰富的功能和灵活性,用于定义Controller层的请求处理方法、处理不同类型的请求和参数。通过使用这些注解,可以轻松地构建功能强大的Controller层。