SpringBoot-URL路由:@Controller和@RequestMapping

來源:互聯網
上載者:User

標籤:分享   函數   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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.