SpringBoot中获取请求头,请求体,路径中的值

导读:本篇文章讲解 SpringBoot中获取请求头,请求体,路径中的值,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

获取请求头中的值:

获取请求头中的Accept

@GetMapping("/getHead")
@ResponseBody
public void getHead(@RequestHeader("Accept") String accept) {
    System.out.println(accept);
}

获取请求体中的值:

    @RequestMapping(value = "/test",method = RequestMethod.POST)
    public Person getRest(@RequestBody Person person){
        System.out.println(person);
        return person;
    }

SpringBoot中获取请求头,请求体,路径中的值

获取url路径中的值:

@RequestParam

用在get请求中,案例如下

    @RequestMapping(value = "/test",method = RequestMethod.GET)
    public String getRequest(@RequestParam String dog){
        return dog;
    }

我们来用postman测试一下,一切正常

SpringBoot中获取请求头,请求体,路径中的值

我们还可以用@RequestParam(name = “xxx”)指定传过来的属性,依旧这段代码(多了个指定名字),看代码和结果

    @RequestMapping(value = "/test",method = RequestMethod.GET)
    public String getRequest(@RequestParam(name = "cat") String dog){
        return dog;
    }

SpringBoot中获取请求头,请求体,路径中的值

@PathVariable

用在rest请求的接口中美滋滋,以get请求为例,为了效果我故意把路径变量和形参不一样,方便理解

    @RequestMapping(value = "/test/{person}",method = RequestMethod.GET)
    public String getRest(@PathVariable(name = "person") String dog){
        return dog;
    }

SpringBoot中获取请求头,请求体,路径中的值

@CookieValue 

获取cookie的值,与上类似,自己探索吧

@RequestAttribute

获取request设置的属性

@Controller
public class NewController {
    @RequestMapping(value = "/")
    public String test(HttpServletRequest request){
        request.setAttribute("name","li4");
        return "forward:/testAttribute"; //转发到testAttribute页面
    }
    @ResponseBody
    @RequestMapping("testAttribute")
    public String test2(@RequestAttribute("name") String attribute){
        return attribute;
    }
}

SpringBoot中获取请求头,请求体,路径中的值  以上为常用的参数注解,如有补充或指出错误,请赐教 

 

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/106016.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!