SSM學習——SpringMVC(4)

處理請求數據

請求處理方法簽名
1)Spring MVC 通過分析處理方法的簽名,HTTP請求信息綁定到處理方法的相應人蔘中。
2)Spring MVC 對控制器處理方法簽名的限制是很寬鬆的,幾乎可以按喜歡的任何方式對方法進行簽名。
3)必要時可以對方法及方法入參標註相應的註解( @PathVariable 、@RequestParam、@RequestHeader 等)。
4)Spring MVC 框架會將 HTTP 請求的信息綁定到相應的方法入參中,並根據方法的返回值類型做出相應的後續處理。
@RequestParam註解
映射請求參數到請求處理方法的形參

Html代碼
  <a href="testRequestParam?username=Tom&age=22">Test RequestParam</a>
java代碼
   @RequestMapping("testRequestParam")
    public String testRequest(@RequestParam("username") String username,@RequestParam("age")Integer age){
        System.out.println("username:"+username+" "+"age:"+age);
        return "success";
    }

開始測試:
在這裏插入圖片描述
測試結果:
在這裏插入圖片描述
在這裏插入圖片描述
@RequestParam標註的形參必須要賦值,必須要能從請求參數對象中獲取到對應的請求參數
可以使用required來設置該參數不是必須的
代碼如下:

  @RequestMapping("testRequestParam")
    public String testRequest(@RequestParam("username") String username,
                              @RequestParam(value = "age",required = false)Integer age){
        System.out.println("username:"+username+" "+"age:"+age);
        return "success";
    }

測試結果如下:
在這裏插入圖片描述
隱藏的問題:int類型不能賦值爲null,但是Integer可以,所以在編寫的時候需要注意
可以使用defaultValue來指定一個默認值取代null

@RequestMapping("testRequestParam")
    public String testRequest(@RequestParam("username") String username,
                              @RequestParam(value = "age",required = false)Integer age){
        System.out.println("username:"+username+" "+"age:"+age);
        return "success";
    }

測試結果如下
在這裏插入圖片描述
@RequestHeader
映射請求頭信息到請求處理方法的形參中

 @RequestMapping("testRequestHeader")
    public String testRequestHeader(@RequestHeader("Accept-language") String username){
        System.out.println("username:"+username);
        return "success";
    }

測試結果:
在這裏插入圖片描述
@CookieValue

/**
	 * @CookieValue  映射cookie信息到請求處理方法的形參中
	 */
	@RequestMapping("/testCookieValue")
	public String testCookieValue(@CookieValue("JSESSIONID")String sessionId) {
		System.out.println("sessionid:" + sessionId);
		return "success";
	}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章