
DispatcherServlet 攔截請求。HandlerMapping 根據 URL 找到 Controller(Handler)。HandlerAdapter 執行 Controller 方法。ModelAndView 或視圖名。ViewResolver 解析邏輯視圖名為具體 View。@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping(value = "/register")
public String register() {
return "user/register"; // 邏輯視圖名
}
}
@RequestMapping 定義基礎路徑前綴。@RequestMapping 定義相對路徑,組合成完整映射 /user/register。| 模式 | 匹配示例 | 說明 |
|---|---|---|
/user/*/create | /user/aaa/create, /user/bbb/create | * 匹配單層路徑 |
/user/**/create | /user/create, /user/aaa/bbb/create | ** 匹配任意層路徑 |
/user/create?? | /user/createaa, /user/createbb | ? 匹配單字符 |
/user/{userId} | /user/123, /user/abc | 佔位符綁定 @PathVariable |
/company/{companyId}/user/{userId}/detail | /company/123/user/456/detail | 多佔位符 |
@RequestMapping("/{userId}")
public ModelAndView showDetail(@PathVariable("userId") String userId) {
ModelAndView mav = new ModelAndView("user/showDetail");
mav.addObject("user", userService.getUserById(userId));
return mav;
}
若 @PathVariable 不指定名稱,**必須編譯時保留參數名**(javac -parameters 或 -g),否則運行時報錯,不建議省略。
@RequestMapping(value="/delete", method=RequestMethod.POST)
public String delete(@RequestParam("userId") String userId) { ... }
同一 URL 不同 Method 可映射到不同處理方法,實現 RESTful 風格。
// 必須包含 userId 參數
@RequestMapping(value="/delete", params="userId")
public String delete(@RequestParam("userId") String userId) { ... }
// 僅接受 Content-Type 為 text/* 的請求
@RequestMapping(value="/show", headers="content-type=text/*")
public String show() { ... }
| 表達式 | 含義 |
|---|---|
param1 | 必須包含參數 param1 |
!param1 | 不得包含參數 param1 |
param1!=value1 | 包含 param1 但值不等於 value1 |
{"param1=value1","param2"} | 同時滿足 param1=value1 且包含 param2 |
headers 同理,針對請求頭字段匹配。
Spring MVC 透過 @RequestMapping 的組合條件(URL、Method、Params、Headers)實現極其靈活的請求分發,支援 RESTful、傳統表單、AJAX 等多種交互風格,掌握三大維度組合技巧是高效開發 Controller 的關鍵。