Spring Boot筆記(一)——註解
阿新 • • 發佈:2018-12-09
[email protected] 用於定義控制器類,在spring 專案中由控制器負責將使用者發來的URL請求轉發到對應的服務介面(service層)。 [email protected] 註解等價於@[email protected]的結合,使用這個註解的類裡面的方法都以json格式輸出。 [email protected] 提供路由資訊,負責URL到Controller中的具體函式的對映。 這個註解會將 HTTP 請求對映到 MVC 和 REST 控制器的處理方法上。 要配置 Web 請求的對映,就需要你用上 @RequestMapping 註解。
@RequestMapping("/home")
public class IndexController {
@RequestMapping("/")
String get() {
//mapped to hostname:port/home/
return "Hello from get";
}
@RequestMapping("/index")
String index() {
//mapped to hostname:port/home/index/
return "Hello from index" ;
}
}
如上述程式碼所示,到 /home 的請求會由 get() 方法來處理,而到 /home/index 的請求會由 index() 來處理。
@RequestMapping("/home")
public class IndexController {
@RequestMapping(value = {
"",
"/page",
"page*",
"view"
"view/*"
})
String indexMultipleMapping() {
return "Hello from index multiple mapping." ;
}
}
如上述程式碼所示,可以將多個請求對映到一個方法上去,只需要新增一個帶有請求路徑值列表的 @RequestMapping 註解就行了。前面這段程式碼中,如下的這些 URL 都會由 indexMultipleMapping() 來處理: localhost:8080/home localhost:8080/home/ localhost:8080/home/page localhost:8080/home/pageabc localhost:8080/home/view/ localhost:8080/home/view/view