基本注解@RequestParam @RequestHeader @CookieValue 的基本用法 Spring MVC笔记(二)

  • @RequestParam 来映射请求参数。
  • value 值即请求参数的参数名
  • required 该参数是否必须。默认为true
  • defaultValue 请求参数的默认值

后端代码:


/*
    * 1、@RequestMapping除了可以修饰方法还可以修饰类
    * 2、类定义处相对于根目录,方法定义处相对于类
    * 3、@RequestParam接受传统URL传值
    * */
    @RequestMapping(value = "/helloWorld",method = RequestMethod.GET)
    public String helloWorld(@RequestParam(value = "name") String name, @RequestParam(value = "age",required = false,defaultValue = "0") Integer age){
        System.out.println("testRequestParam, username=  " + name + "  age=  " + age);
        return SUCCESS;
    }

前端代码:


<form action="/hello/testRequestParam" method="post">
    username: <input type="text" name="username">
    <br>
    age: <input type="number" name="age">
    <br>
    <input type="submit" value="提交"/>
</form>

  • 使用@RequestHeader绑定请求报头的属性值
  • 使用方法同@RequestParam相同

    @RequestMapping(value = "/helloWorld",method = RequestMethod.GET)
    public String helloWorld(@RequestHeader("Accept-Encoding") String encoding){
        return SUCCESS;
    }

  • 使用@CookieValue绑定请求中的Cookie值
  • 使用方法同@RequestParam相同

    @RequestMapping(value = "/helloWorld",method = RequestMethod.GET)
    public String helloWorld(@CookieValue(value="sessionId",required  = false)){
        return SUCCESS;
    }

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容