zoukankan      html  css  js  c++  java
  • Spring 注解之@RequestHeader注解:获取请求头参数

    基本用法

      Spring MVC提供了 @RequestHeader注解,其作用是将请求头中的参数值映射到控制器的参数中。常用属性如下:

    • name:header值被绑定到的参数名称(The name of the request header to bind to)。只有此属性时,可以省略name,简写为@RequestHeader("host")
    • required:boolean类型,默认为true,即请求头中必须包含此参数。
    • defaultParameter:为请求头中的参数提供默认值,如果拿不到之,就将此值赋给控制器的参数。

    测试用例

      创建一个controller,读取请求头中的两个参数:

    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestHeader;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @RequestMapping("hello")
    public class HelloController {
    
        @PostMapping("/getHeader.do")
        public String getHeader(@RequestHeader("host") String host,
                                @RequestHeader(name = "my-header", required = false, 
                                defaultValue = "3") String myHeader){
            System.out.println("host---"+host);
            System.out.println("accept---"+myHeader);
            return "success:" + myHeader;
        }
    
    }
    

      上面的函数getHeader,把request header中的参数 host的值绑定到参数host上了, my-header 的值绑定到参数myHeader上。在IDEA中创建一个基于.http文件的测试用例:

    ### 获取请求头中的参数,header随机故意写错
    POST http://localhost:8087/wiener/hello/getHeader.do
    Content-Type: application/json
    my-header1: givenHeader
    
    {}
    
    ###
    
    ### 获取请求头中的参数,header书写正确
    POST http://localhost:8087/wiener/hello/getHeader.do
    Content-Type: application/json
    my-header: givenHeader
    
    {}
    
    ###
    

      依次执行如上两个请求,得到的执行结果如下:

    host---localhost:8087
    accept---3
    host---localhost:8087
    accept---givenHeader
    

      从执行结果得知,header中的参数可以写错,而且写错时,打印的结果是默认值3。

    小结

      以上就是这篇文章的全部内容了,希望本文对道友的学习或者工作能带来一定的帮助,如有疑问请留言交流。Wiener在此祝各位生活愉快!工作顺利!


      读后有收获,小礼物走一走,请作者喝咖啡。

    赞赏支持

  • 相关阅读:
    木块问题(The Blocks Problem,Uva 101)
    知识点
    大理石在哪儿(Where is the Marble?,Uva 10474)
    C++结构体
    踪电子表格中的单元格(Spreadsheet Tracking, ACM/ICPC World Finals 1997, UVa512)
    救济金发放(The Dole Queue, UVa 133)
    指针问题
    刽子手游戏(Hangman Judge, UVa 489)
    【poj3278】Catch That Cow
    【CodeVS1226】倒水问题
  • 原文地址:https://www.cnblogs.com/east7/p/15390392.html
Copyright © 2011-2022 走看看