SpringBoot核心技术-Web开发-请求参数

1、普通参数与基本注解

1.1 注解

@PathVariable、@RequestHeader、@ModelAttribute、@RequestParam、@MatrixVariable、@CookieValue、@RequestBody

@RestController
public class ParameterTestController {


    //  car/2/owner/zhangsan
    @GetMapping("/car/{id}/owner/{username}")
    public Map<String,Object> getCar(@PathVariable("id") Integer id,
                                     @PathVariable("username") String name,
                                     @PathVariable Map<String,String> pv,
                                     @RequestHeader("User-Agent") String userAgent,
                                     @RequestHeader Map<String,String> header,
                                     @RequestParam("age") Integer age,
                                     @RequestParam("inters") List<String> inters,
                                     @RequestParam Map<String,String> params,
                                     @CookieValue("_ga") String _ga,
                                     @CookieValue("_ga") Cookie cookie){


        Map<String,Object> map = new HashMap<>();

//        map.put("id",id);
//        map.put("name",name);
//        map.put("pv",pv);
//        map.put("userAgent",userAgent);
//        map.put("headers",header);
        map.put("age",age);
        map.put("inters",inters);
        map.put("params",params);
        map.put("_ga",_ga);
        System.out.println(cookie.getName()+"===>"+cookie.getValue());
        return map;
    }
    @PostMapping("/save")
    public Map postMethod(@RequestBody String content){
        Map<String,Object> map = new HashMap<>();
        map.put("content",content);
        return map;
    }

}

/car/{id}/owner/{username}

@PathVariable("id") Integer id:将路径中的{id}和参数Integer id进行绑定

@PathVariable Map<String,String> pv:不加参数的话,将路径中所有的{}的值保存在pv这个map中,key是{}的字段名,value是{}实际请求时的值

@RequestHeader("User-Agent") String userAgent:将请求头的User-Agengt的值和userAgent绑定

@RequestHeader Map<String,String> header:将请求头的所有字段和值存在header这个map中

@RequestParam("age") Integer age:将请求参数age和Integer age绑定。这个请求参数来自HTTP请求体或请求Url的QueryString。需要注意如果是请求体的参数提交时,Content-Type 应为 application/x-www-form-urlencoded表单提交默认形式)。如果以json格式,后端应该使用@RequestBody ,否则接收不到json中的字段值。

@RequestBody String content:将请求体的内容与content绑定,一般用于处理Content-Type不为 application/x-www-form-urlencoded编码格式的数据,比如:application/json、application/xml等类型的数据。当然,application/x-www-form-urlencoded编码格式@RequestBody 也能接收到,后端拿到的是username=ffffffffff&age=111这种形式的数据,类似url格式的属性名+值。就application/json类型的数据而言,使用注解@RequestBody可以将body里面所有的json数据传到后端,后端再进行解析。

@CookieValue("_ga") String _ga:将请求头中名为_ga的Cookie的值与_ga绑定。

@CookieValue("_ga") Cookie cookie:将请求头中名为_ga的Cookie与_ga对象绑定。

@RequestAttribute@RequestAttribute("msg") String msg:将请求对象中的属性值,绑定到msg对象。和在方法里写request.getAttribute("msg")效果一样。此注解没有Map。

    @GetMapping("/goto")
    public String pageTo(HttpServletRequest request) {
        request.setAttribute("msg","成功了");
        return "forward:/success";
    }

    @GetMapping("/success")
    @ResponseBody
    public Map success(@RequestAttribute("msg") String msg,HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        map.put("annotation method", msg);
        map.put("request method", request.getAttribute("msg"));
        return map;
    }

矩阵变量使用场景:如果把cookie 禁用掉,session 里面的内容怎么找到

cookie 和 session 的机制就是,每个用户有一个session,session里面保存一个k-v的值,然后每个人的session都有一个jsessionid。这个jsessionid 会被保存在cookie里面,每次用户发送请求cookie 都会携带jsessionid ,如果把cookie 禁用掉,我们要获取session的k获取v ,肯定要通过jsessionid来拿到这个session对象,但是jsession有保存在cookie 所以无法从session对象的v
这里我们可以使用矩阵变量来获取 session 如 /user;jessionid=xxx   用过url 重写,把cookie的值使用矩阵变量的方式进行传递

/cars/sell;low=34;brand=byd,audi,yd

@GetMapping("/cars/{path}")

@MatrixVariable("low") Integer low:将路径中的矩阵变量low绑定到 Integer low,需要注意的是

与矩阵变量用分号连接的路径,例如sell,要在GetMapping中写成写在{}中,如{path}。即矩阵变量必须有url路径变量中才能被解析。

 /boss/1;age=20/2;age=10 矩阵变量名重复的情况

@GetMapping("/boss/{bossId}/{empId}")

(@MatrixVariable(value = "age",pathVar = "bossId") Integer bossAge,

@MatrixVariable(value = "age",pathVar = "empId") Integer empAge)

将路径变量设为不同的变量名,同时@MatrixVariable的pathVar属性赋值为路径变量名加以区分。

    //1、语法: 请求路径:/cars/sell;low=34;brand=byd,audi,yd
    //2、SpringBoot默认是禁用了矩阵变量的功能
    //      手动开启:原理。对于路径的处理。UrlPathHelper进行解析。
    //              removeSemicolonContent(移除分号内容)支持矩阵变量的
    //3、矩阵变量必须有url路径变量才能被解析
    @GetMapping("/cars/{path}")
    public Map carsSell(@MatrixVariable("low") Integer low,
                        @MatrixVariable("brand") List<String> brand,
                        @PathVariable("path") String path){
        Map<String,Object> map = new HashMap<>();

        map.put("low",low);
        map.put("brand",brand);
        map.put("path",path);
        return map;
    }

    // /boss/1;age=20/2;age=10

    @GetMapping("/boss/{bossId}/{empId}")
    public Map boss(@MatrixVariable(value = "age",pathVar = "bossId") Integer bossAge,
                    @MatrixVariable(value = "age",pathVar = "empId") Integer empAge){
        Map<String,Object> map = new HashMap<>();

        map.put("bossAge",bossAge);
        map.put("empAge",empAge);
        return map;

    }

需要注意:

SpringBoot默认是禁用了矩阵变量的功能
    手动开启:原理。对于路径的处理。UrlPathHelper进行解析。
     removeSemicolonContent(移除分号内容)支持矩阵变量的

具体实现:

1、在自己定义的配置类中,@Bean注入一个WebMvcConfigurer接口的实现类

@Configuration(proxyBeanMethods = false)
public class MyConfig {

    @Bean("myWebMvcConfigurer")
    public WebMvcConfigurer webMvcConfigurer(){
        return new WebMvcConfigurer() {
            @Override
            public void configurePathMatch(PathMatchConfigurer configurer) {
                UrlPathHelper urlPathHelper = new UrlPathHelper();
                urlPathHelper.setRemoveSemicolonContent(false);
                configurer.setUrlPathHelper(urlPathHelper);
            }
        };
    }
}

2、将配置类实现WebMvcConfigurer接口,重写configurePathMatch方法

@Configuration(proxyBeanMethods = false)
public class MyConfig implements WebMvcConfigurer {

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        UrlPathHelper urlPathHelper = new UrlPathHelper();
        urlPathHelper.setRemoveSemicolonContent(false);
        configurer.setUrlPathHelper(urlPathHelper);
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值