標籤:分享 函數 http請求 ppi img code es2017 應用程式 tco
SpringBoot定義URL處理方法:@Controller和@RequestMapping
@Controller標註的類表示的是一個處理HTTP請求的控制器(即MVC中的C),該類中所有被@RequestMapping標註的方法都會用來處理對應URL的請求。
在SpringMVC架構中,使用@RequsetMapping標註可以將URL與處理方法綁定起來,例如:
@RestControllerpublic class HelloworldRestController { @RequestMapping("/") public String helloworld(){ return "hello world"; } @RequestMapping("/hello") @ResponseBody public String hello(){ return "fpc"; }}
HelloworldRestController類被@Controller標註,其中的兩個方法都被@RequestMapping標註,當應用程式運行後,在瀏覽器中訪問:localhost:8089,請求會被SpringMVC架構分發到hellworld()方法進行處理。同理輸入localhost:8089/hello會交給hello()方法處理。
@ResponseBody標註表示處理函數直接將函數的傳回值傳到瀏覽器端顯示。
運行結果:
輸入localhost:8089:
輸入loalhost:8089/hello:
@RequestMapping標註類
@RequestMapping標註同樣可以加在類上:
@RestController@RequestMapping("/index")public class HelloworldRestController { @RequestMapping("/") public String helloworld(){ return "hello world"; } @RequestMapping("/hello") @ResponseBody public String hello(){ return "fpc"; }}
hello()方法綁定的URL路徑是/index/hello
運行結果:
如果直接存取:localhost:8089/hello:
如果訪問:localhost:8089/index/hello:
提示:每一個類都可以包含一個或者多個@RequestMapping標註的方法,通常我們會將商務邏輯相近的URL放在同一個Controller中處理。
SpringBoot-URL路由:@Controller和@RequestMapping