注解@MatrixVariable

使用注解@MatrixVariable获取矩阵变量。

使用查询字符串

先看个 请求路径占位符/{xxx}@PathVariable@RequestParam的例子。
新建Spring项目:demo4,新建控制器com.example.boot.controller.Demo4Controller,如下,

@RestController
public class MetrixController {
    @GetMapping("/person/{path}")
    public Map<String,Object> get(@PathVariable("path") String path,
                                  @RequestParam("name") String name,
                                  @RequestParam("hobbies") List<String> hobbies){
        Map<String,Object> map = new HashMap<>();
        map.put("name",name);
        map.put("hobbies",hobbies);
        map.put("path",path);
        return map;
    }
}

resources.static下新建页面index.html,如下,

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
    <a href="/person/info?name=zhangsan&hobbies=computer,basketball,ping-pong">测试@RequestParam#get()</a>
</body>
</html>

在这里插入图片描述
/person/info?name=zhangsan&hobbies=computer,basketball,ping-pong,其中

  • /person/{path} + @PathVariable("path") String path,使用@PathVariable获取请求路径中的占位符{path}
  • @RequestParam("name") String name@RequestParam("hobbies") List<String> hobbies,使用@RequestParam获取查询字符串:namehobbies
使用矩阵变量

使用查询字符串:/person/info?name=zhangsan&hobbies=computer,basketball,ping-pong
而使用矩阵变量:/person/info;name=zhangsan;hobbies=computer,basketball,ping-pong
接下来看看如何使用@MatrixVariable获取矩阵变量。

SpringBoot默认是禁用矩阵变量的,所以在使用@MatrixVariable之前,需要开启矩阵变量这项功能。
至于怎么开启,SpringBoot官网参考文档中有这么一段话,

If you want to keep those Spring Boot MVC customizations and make more MVC customizations (interceptors, formatters, view controllers, and other features), you can add your own @Configuration class of type WebMvcConfigurer but without @EnableWebMvc.

到类WebMvcAutoConfiguration源码里去,有个UrlPathHelper类。

@Configuration(
    proxyBeanMethods = false
)
@Import({WebMvcAutoConfiguration.EnableWebMvcConfiguration.class})
@EnableConfigurationProperties({WebMvcProperties.class, WebProperties.class})
@Order(0)
public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer, ServletContextAware {
	//...
	public void configurePathMatch(PathMatchConfigurer configurer) {
           if (this.mvcProperties.getPathmatch().getMatchingStrategy() == MatchingStrategy.PATH_PATTERN_PARSER) {
               configurer.setPatternParser(WebMvcAutoConfiguration.pathPatternParser);
           }

           configurer.setUseSuffixPatternMatch(this.mvcProperties.getPathmatch().isUseSuffixPattern());
           configurer.setUseRegisteredSuffixPatternMatch(this.mvcProperties.getPathmatch().isUseRegisteredSuffixPattern());
           this.dispatcherServletPath.ifAvailable((dispatcherPath) -> {
               String servletUrlMapping = dispatcherPath.getServletUrlMapping();
               if (servletUrlMapping.equals("/") && this.singleDispatcherServlet()) {
                   UrlPathHelper urlPathHelper = new UrlPathHelper();
                   urlPathHelper.setAlwaysUseFullPath(true);
                   configurer.setUrlPathHelper(urlPathHelper);
               }

           });
       }
        //...
}

进入UrlPathHelper类,有个布尔类型的属性removeSemicolonContent,且默认为true,即默认移除请求路径上的;的内容。

public class UrlPathHelper {
	//...
    private boolean removeSemicolonContent = true;
    //...
    public void setRemoveSemicolonContent(boolean removeSemicolonContent) {
        this.checkReadOnly();
        this.removeSemicolonContent = removeSemicolonContent;
    }
    //...

现在我们要使用矩阵变量,当然就不应该移除分号的内容,即应将removeSemicolonContent设置为false。为此,需要自定义配置类来覆盖SpringBoot默认配置。
com.example.boot下新建配置类config.MyConfig,有两种配置方式,

  • 第一种,实现接口WebMvcConfigurer,覆盖方法configurePathMatch
@Configuration
public class MyConfig implements WebMvcConfigurer {
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        UrlPathHelper urlPathHelper = new UrlPathHelper();
        urlPathHelper.setRemoveSemicolonContent(false);
        configurer.setUrlPathHelper(urlPathHelper);
    }
}
  • 第二种,自定义WebMvcConfigurer类型组件并添加到容器中。
@Configuration
public class MyConfig {
    @Bean
    public WebMvcConfigurer webMvcConfigurer(){
        return new WebMvcConfigurer() {
            @Override
            public void configurePathMatch(PathMatchConfigurer configurer) {
                UrlPathHelper urlPathHelper = new UrlPathHelper();
                urlPathHelper.setRemoveSemicolonContent(false);
                configurer.setUrlPathHelper(urlPathHelper);
            }
        };
    }
}

接下来,修改Demo4Controller和index.html的内容,如下,

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
    <a href="/person/info;name=zhangsan;hobbies=computer,basketball,ping-pong">测试@MatrixVariable#get()</a>
</body>
</html>
package com.example.boot.controller;

import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class Demo4Controller {
    @GetMapping("/person/{path}")
    public Map<String,Object> get(@PathVariable("path") String path,
                                      @MatrixVariable("name") String name,
                                      @MatrixVariable("hobbies") List<String> hobbies){
        Map<String,Object> map = new HashMap<>();
        map.put("path",path);
        map.put("name",name);
        map.put("hobbies",hobbies);
        return map;
    }
}

启动应用,点击链接访问接口,结果如下。
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值