@requestMapping

轉自https://blog.csdn.net/kobejayandy/article/details/12690041web

 

Spring經過@Controller註解找到相應的控制器類後,還須要知道控制器內部對每個請求是如何處理的,這就須要使用@RequestMapping註解類型,它用於映射一個請求或一個方法。使用時,能夠標註在一個方法或一個類上。spring

1. 標註在方法上:做爲請求處理方法在程序接收到對應的URL請求時被調用:app

  1. package com.itheima.controller;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. ...
  5. @Controller
  6. public class FirstController{
  7. @RequestMapping(value="/firstController")
  8. public ModelAndView handleRequest(HttpServletRequest request,
  9. HttpServletResponse response) {
  10. ...
  11. return mav;
  12. }
  13. }

此時,能夠經過地址:http://localhost:8080/chapter12/firstController訪問該方法!spa

2. 標註在類上:該類中的全部方法都將映射爲相對於類級別的請求,表示該控制器所處理的全部請求都被映射到value屬性值所指定的路徑下。.net

  1. package com.itheima.controller;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. ...
  5. @Controller
  6. @RequestMapping(value="/hello")
  7. public class FirstController{
  8. @RequestMapping(value="/firstController")
  9. public ModelAndView handleRequest(HttpServletRequest request,
  10. HttpServletResponse response) {
  11. ...
  12. return mav;
  13. }
  14. }

因爲在類上添加了@RequestMapping註解,而且其value屬性值爲「/hello」,因此上述代碼方法的請求路徑將變爲:http://localhost:8080/chapter12/hello/firstController。code

@RequestMapping註解除了能夠指定value屬性外,還能夠指定其餘一些屬性,以下表所示。blog

 

表中全部屬性都是可選的,但其默認屬性是value。當value是其惟一屬性時,能夠省略屬性名。下面兩種標註的含義相同:string

               @RequestMapping(value="/firstController")it

               @RequestMapping("/firstController")io

相關文章
相關標籤/搜索