學習SpringMVC——如何獲取請求引數
阿新 • • 發佈:2018-11-19
@RequestParam
@PathVariable
@QueryParam
@CookieValue
@ModelAndView
@ModelAttribute
一、spring mvc如何匹配請求路徑——“請求路徑哪家強,RequestMapping名遠揚”
@RequestMapping是用來對映請求的,比如get請求,post請求,或者REST風格與非REST風格的。 該註解可以用在類上或者方法上,如果用於類上,表示該類中所有方法的父路徑。
@Controller的註解,該註解在SpringMVC 中,負責處理由DispatcherServlet 分發的請求,它把使用者請求的資料經過業務處理層處理之後封裝成一個Model ,然後再把該Model 返回給對應的View 進行展示。
RequestMapping可以實現模糊匹配路徑,比如: ?:匹配一個字元 *:匹配任意字元 **:匹配多層路徑 /springmvc/**/lastTest 就可以匹配/springmvc/firstTest/secondTest/lastTest這樣的路徑
二、spring mvc如何獲取請求的引數——“八仙過海,各顯神通”
1. @PathVariable
該註解用來對映請求URL中繫結的佔位符。通過@PathVariable可以將URL中佔位符的引數繫結到controller處理方法的入參中
@RequestMapping("/testPathVariable/{id}") public String testPathVariable(@PathVariable(value="id") Integer id){ System.out.println("testPathVariable:" + id); return SUCCESS; }
<a href="springmvc/testPathVariable/1">testPathVariable</a><br/><br/>
2. @RequestParam
該註解也是用來獲取請求引數的。那麼該註解和@PathVariable有何不同呢?
@RequestMapping(value="/testRequestParam") public String testRequestParam(@RequestParam(value="username") String username, @RequestParam(value="age", required=false, defaultValue="0") int age){ System.out.println("testRequestParam" + " username:" + username + " age:" +age); return SUCCESS; }
注:@PathVariable和@RequestParam之間的一些區別
請求引數是以鍵值對出現的,我們通過@RequestParam來獲取到如username或age後的具體請求值
增刪改都是通過post方式傳送出去的
總結下,如何傳送put和delete的請求:
1.在web.xml中配置HiddenHttpMethodFilter
<!-- 配置HiddenHttpMethodFilter:可以把POST請求轉為DELETE或POST請求 --> <filter> <filter-name>HiddenHttpMethodFilter</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <filter-mapping> <filter-name>HiddenHttpMethodFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
<input type="hidden" name="_method" value="DELETE"/>
2.傳送post請求
3.請求中是個隱藏域,name為”_mothod”,value為put或delete
3. @CookieValue
也是一種對映,對映的是一個Cookie值。
@RequestMapping("/hellocookie") public String testCookieValue(@CookieValue("JSESSIONID") String cookieValue){ System.out.println("testCookieValue: " + cookieValue); return "success"; }
index.jsp介面上新增連結
<a href="hellocookie">hellocookie</a>