springMVC學習總結(二)路徑映射和請求方法限定
一、路徑映射
無參數的訪問路徑
-
對springmvc項目的訪問路徑,是由根路徑和子路徑組成;在注解式開發中,根路徑標注在類名之上,子路徑標注在方法名之上,例:
@Controller @RequestMapping(value = "/rootpath") public class Demo01Controller { @RequestMapping(value = "/childpath.action") public ModelAndView test(){ System.out.println("訪問成功!"); ModelAndView mv = new ModelAndView(); mv.addObject("message", "測試成功"); mv.setViewName("hello"); return mv; } }
在這個例子中:
根路徑是類名上方的 RequestMapping(value = "/rootpath")
;
方法名上方的 RequestMapping(value = "/rootpath")
因此該方法的訪問路徑是:http://localhost:8080/rootpath/childpath.action
路徑中有參數的訪問路徑
-
如果我們想通過url傳遞一個或多個參數到后台,在不考慮安全問題的情況下可以使用url的方式攜帶參數訪問,比如我們要獲取一個id值,我們后台編碼如下:
@Controller @RequestMapping(value = "/rootpath",method = RequestMethod.GET) public class Demo01Controller { @RequestMapping(value = "/childpath/{id}") public ModelAndView test(@PathVariable String id){ System.out.println("get提交的參數為:"+id); ModelAndView mv = new ModelAndView(); mv.addObject("message", "測試成功"); mv.setViewName("hello"); return mv; } }
此時的訪問路徑是:
http://localhost:8080/rootpath/childpath.action/3.action
這個url中傳遞的參數值是id=1
-
當有多個參數的時候,只要方法的參數名與路徑中的參數命名一一對應便可一一對應的取到值,如:
@Controller @RequestMapping(value = "/rootpath",method = RequestMethod.GET) public class Demo01Controller { @RequestMapping(value = "/childpath/{id}/{username}") public ModelAndView test(@PathVariable String id,@PathVariable String username){ System.out.println("get提交的參數id為:"+id+"用戶名為:"+username); ModelAndView mv = new ModelAndView(); mv.addObject("message", "測試成功"); mv.setViewName("hello"); return mv; } }
此時的訪問路徑是:
http://localhost:8080/rootpath/childpath.action/3/sunwukong.action
這個url中傳遞的參數值是id=1
,用戶名為:sunwukong
-
二、方法限定
- 方法的限定編碼位置同樣在注解@RequestMapping()中,如下圖:
方法名上方的:method = RequestMethod.GET
是對請求方法的限定,可選擇的常用方法有以下幾種: