引言
在 Spring Boot 應用程序中,Controller 是 MVC 架構(gòu)模式中的核心組件之一,負責處理 HTTP 請求并返回響應結(jié)果。為了更好地映射請求、解析請求參數(shù)、執(zhí)行業(yè)務邏輯和生成視圖或 JSON 數(shù)據(jù),Controller 中廣泛使用了各種注解。本文將全面梳理 Spring Boot 中 Controller 接口所使用的各類注解及其具體使用案例。
一、Controller 類級別的注解
1. 控制器類注解
@Controller
import org.springframework.stereotype.Controller;
@Controller
public class MyController {
// ...
}
用途:標記一個類作為Spring MVC的控制器,此類中包含的方法將被映射為HTTP請求處理器。
2. RESTful控制器注解
@RestController
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyRestController {
// ...
}
用途:@RestController是一個組合注解,它同時包含了@Controller和@ResponseBody,意味著該控制器的所有方法都將直接返回JSON、XML或者其他類型的數(shù)據(jù)而不是視圖名。
二、路徑映射注解
@RequestMapping
@RequestMapping
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/api/v1")
public class MyApiV1Controller {
@RequestMapping("/users")
public ResponseEntity<List<User>> getAllUsers() {
// ...
}
}
用途:它可以放在類或方法上,用于指定控制器類或者方法處理的請求的基本URL路徑。
三、 方法級別的路徑映射注解
@GetMapping, @PostMapping, @PutMapping, @DeleteMapping
import org.springframework.web.bind.annotation.*;
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) {
// ...
}
@PostMapping("/users")
public ResponseEntity<User> createUser(@RequestBody User user) {
// ...
}
@PutMapping("/users/{id}")
public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User updatedUser) {
// ...
}
@DeleteMapping("/users/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
// ...
}
用途:這些注解分別對應HTTP的GET、POST、PUT和DELETE方法,用于精確映射HTTP請求到相應的方法。
四、 方法參數(shù)注解
@PathVariable
@GetMapping("/users/{userId}/details")
public UserDetails getUserDetails(@PathVariable("userId") Long userId) {
// ...
}
用途:從URL模板變量中提取值,并將其綁定到方法參數(shù)。
@RequestParam
@GetMapping("/search")
public List<User> searchUsers(
@RequestParam(name = "name", required = false) String name,
@RequestParam(defaultValue = "10") int limit) {
// ...
}
用途:從請求的查詢參數(shù)中獲取值。
@RequestBody
@PostMapping("/users")
public User createUser(@RequestBody User newUser) {
// ...
}
用途:將整個HTTP請求體轉(zhuǎn)換成Java對象。
@RequestHeader
@GetMapping("/headers")
public String getHeaderValue(@RequestHeader("Authorization") String authHeader) {
// ...
}
用途:從請求頭中提取指定名稱的值。
@CookieValue
@GetMapping("/cookies")
public String getCookie(@CookieValue(value = "JSESSIONID", defaultValue = "") String sessionId) {
// ...
}
用途:從請求的cookie中提取指定名稱的值。
@ModelAttribute
@ModelAttribute("userForm")
public UserForm setUpUserForm() {
return new UserForm();
}
@PostMapping("/register")
public String register(@ModelAttribute("userForm") UserForm userForm) {
// ...
}
作用:用于將請求參數(shù)自動綁定到模型屬性對象,或者在方法體內(nèi)填充模型屬性。文章來源:http://www.zghlxwxcb.cn/news/detail-856989.html
五、其他增強型注解
@ModelAttribute 用于方法參數(shù)時,它可以從模型中查找已有的屬性,或者通過調(diào)用方法來創(chuàng)建新的屬性。
@Valid 結(jié)合 JSR-303/JSR-349 Bean Validation 使用,對方法參數(shù)進行數(shù)據(jù)校驗。
@PostMapping("/register")
public String register(@Valid @ModelAttribute("userForm") UserForm userForm, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
// ...
}
// ...
}
六、全局異常處理和日志記錄
@ControllerAdvice: 用于創(chuàng)建全局異常處理器,處理所有Controller中拋出的異常。
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<String> handleUserNotFoundException(UserNotFoundException ex) {
// ...
}
}
通過以上示例,我們展示了Spring Boot中Controller接口常見的注解及其實際應用場景。根據(jù)具體需求,開發(fā)者可以選擇合適的注解以構(gòu)建功能完備且健壯的RESTful API。文章來源地址http://www.zghlxwxcb.cn/news/detail-856989.html
到了這里,關(guān)于Spring Boot 中 Controller 接口參數(shù)注解全攻略與實戰(zhàn)案例詳解的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!