【筆記:Spring】@Controller 做了哪些事?
Chuan

  Spring MVC 中最入門、最常使用的 annotation 就是 @Controller 了,它到底做了哪些事?


@Controller 做了哪些事?

@Component

  原始碼中有寫上 @Component,所以也會成為 Spring 框架 IoC 容器管理的 Bean。

處理 HTTP request

  搭配 @RequestMapping@GetMapping 系列等等 annotation,把發送來的 request 轉給對應的 method 處理。

  運作原理:

  • HandlerMapping 會掃描所有有寫 @Controller 的 Bean,把「哪個 URL pattern 對應到哪個 class 的哪個 method 處理」記錄下來
  • DispatherServlet 在接收到 request 時,查找 HandlerMapping 的記錄、找到後交由 HandlerAdapter 去實際呼叫該 method 執行

response html 檔

  return 字串、帶著含資料的 Model,進行後續處理、最後回傳給 client 一個 html 檔。

  運作原理:

  • 把 return 的字串和 method 裡處理的 Model 結合為 ModelAndView
  • 回傳給 HandlerAdapter 和 DispatherServlet
  • 轉交給 ViewResolver 去尋找對應模板
  • 轉交給 View 渲染,完成最後的 html 檔
  • response 給 client

好朋友:@RestController

  response 的不是 html 檔、而是 json 或 xml 格式的資料。


延伸閱讀


參考資料