SpringMVC学习 -- @RequestParam , @RequestHeader , @CookieValue 的使用

使用 @RequestParam 绑定请求参数值:
  • value:参数名 , 仅有一个 value 属性时 , value 可以省略不写。

  • required:是否必须。默认为 true , 表示请求参数中必须包含对应参数, 若不存在 , 抛出异常。

  • defaultValue:与 required 配合使用 , 若 required 为 false , 可以给该参数设置默认初始值。

使用 @RequestHeader 绑定请求头的属性值:
使用 @CookieValue 绑定请求中的 cookie 值:
 1 package com.itdoc.springmvc;
 2 
 3 import org.springframework.stereotype.Controller;
 4 import org.springframework.web.bind.annotation.CookieValue;
 5 import org.springframework.web.bind.annotation.RequestHeader;
 6 import org.springframework.web.bind.annotation.RequestMapping;
 7 import org.springframework.web.bind.annotation.RequestParam;
 8 
 9 /**
10  * @BLOG http://www.cnblogs.com/goodcheap
11  * @DESCRIBE 请求参数,请求头,cookie 注解使用
12  * @AUTHOR WángChéngDá
13  * @DATE 2017-03-09 10:14
14  */
15 @Controller
16 public class TestParam {
17 
18     private final static String SUCCESS = "success";
19 
20     /**
21      * @CookieValue 映射 cookie 值。
22      * ·value: 请求参数的参数名。
23      * ·required: 该请求参数是否必须, 默认为 true, 表示参数中必须包含对应参数, 若不存在, 抛出异常。
24      * ·defaultValue:请求参数默认的初始值, 和 required 配合使用。
25      */
26     @RequestMapping("testCookieValue")
27     public String testCookieValue(@CookieValue("JSESSIONID") String cookieId) {
28         System.out.println("I am TestParam's testCookieValue method... cookie: " +cookieId);
29         return SUCCESS;
30     }
31 
32     /**
33      * @RequestHeader 映射请求头。
34      * ·value: 请求参数的参数名。
35      * ·required: 该请求参数是否必须, 默认为 true, 表示参数中必须包含对应参数, 若不存在, 抛出异常。
36      * ·defaultValue:请求参数默认的初始值, 和 required 配合使用。
37      */
38     @RequestMapping("/testRequestHeader")
39     public String testRequestHeader(@RequestHeader(value = "Accept-Language") String value) {
40         System.out.println("I am TestParam's testRequestHeader method... value: " + value);
41         return SUCCESS;
42     }
43 
44     /**
45      * @RequestParam 映射请求参数。
46      * ·value: 请求参数的参数名。
47      * ·required: 该请求参数是否必须, 默认为 true, 表示参数中必须包含对应参数, 若不存在, 抛出异常。
48      * ·defaultValue:请求参数默认的初始值, 和 required 配合使用。
49      */
50     @RequestMapping("/testRequestParam")
51     public String testRequestParam(@RequestParam("username") String username,
52                                    @RequestParam(value = "age", required = false, defaultValue = "0") int age) {
53         System.out.println("I am testParam's testRequestParam method... username: " + username + ", age: " + age);
54         return SUCCESS;
55     }
56 }

 

posted @ 2017-03-09 11:04  Chinda  阅读(923)  评论(0编辑  收藏  举报