spring boot矩阵变量的使用以及注意事项

184 阅读1分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第1天,点击查看活动详情

矩阵变量在url地址里相当常用,它以键值对的方式出现在url地址中,每个矩阵用;号分隔,如/path;name=ZhangSan;age=15。同一个矩阵有多个值用,号分开,如/path;name=ZhangSan,LiSi;age=15,age=16

spring boot使用矩阵变量,方法如下:

//    /test/sell;low=34;brand=byd,test,haha
    @GetMapping("/test/{path}")
    public Map testsell(@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;
    }

单单写方法是不够的,spring boot矩阵变量要手动开启,不然会报错

我们要访问/test/sell;low=34;brand=byd,test,haha路径结果报错了 在这里插入图片描述 org.springframework.web.bind.MissingMatrixVariableException: Missing matrix variable 'low' for method parameter of type Integer

为啥会这样???

其实在spring boot中,默认禁用掉了矩阵变量的功能,我们需要手动开启。

原理:在spring boot中,对于路径的处理,都是由在自动配置类(WebMvcAutoConfiguration)下的URLPathHelper进行解析的,内置有removeSemicolonContent(移除分号后的内容)属性支持矩阵变量 在这里插入图片描述 我们需要把removeSemicolonContent改为false,矩阵变量才能生效。 我们新建一个WebConfig类,在该类下重写WebMvcConfigurer接口 在这里插入图片描述

@Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        UrlPathHelper urlPathHelper = new UrlPathHelper();
//        不移除矩阵变量分号后的内容
        urlPathHelper.setRemoveSemicolonContent(false);
        configurer.setUrlPathHelper(urlPathHelper);
    }

这样矩阵变量就能生效了。 需要注意的是 由于矩阵变量绑定在路径变量中,所以要写成路径变量的表示法

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

这样就ok了,试一把 在这里插入图片描述

成功了!