SpringBoot中开启矩阵变量

本文介绍如何在SpringBoot中启用矩阵变量功能,并提供两种配置方式:通过@Bean注册WebMvcConfigurer组件和实现WebMvcConfigurer接口。此外,还展示了前端链接及对应的Java控制器示例。

SpringBoot中默认是不可以使用矩阵变量的,需要手动配置。
解决方案有两种

1. 使用@Bean的方式向容器中添加组件

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

2. 让配置类实现WebMvcConfiguer

@Configuration(proxyBeanMethods = false)
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        UrlPathHelper urlPathHelper = new UrlPathHelper();
        // 设置为不移除分号后面的内容
        urlPathHelper.setRemoveSemicolonContent(false);
        configurer.setUrlPathHelper(urlPathHelper);
    }
}

3. 前后端代码

3.1 前端
<a href="/cars/sell;low=34;brand=byd,audi,yd">/cars/sell;low=34;brand=byd,audi,yd</a><br>
3.2 java
    // /cars/sell;low=34;brand=byd,audi,yd
    // SpringBoot默认禁用掉了矩阵变量的功能,需要手动开启
    // 矩阵变量需要保存在路径变量中{}
    @ResponseBody
    @GetMapping("/cars/{path}")
    public Map<String, Object> carsSell(@MatrixVariable("low") Integer low,
                                        @MatrixVariable("brand") List<String> brands,
                                        @PathVariable String path) {
        Map<String, Object> map = new HashMap<>();
        map.put("low", low);
        map.put("brands", brands);
        map.put("path", path);
        return map;
    }
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值