Springboot解析带分号";"的请求参数

1 编写目的

在Springboot微服务风靡大街小巷中各个公司的时候,笔者在某个特殊的场景需要用到分号的形式来分割请求地址中的属性,也就是URL键值对的这种特性来访问Controller接口。比如:"//localhost:8080/getInfo/name=root;pwd=123456;"

用过SpringMVC的朋友,对这个应该不会陌生,SpringMVC默认没有开启该功能,而Springboot默认同样没有开启该功能。

写本文的目的就是告诉大家怎么去解决这个问题。

2 @MatrixVariable注解

Controller方法要接收URL带分号的键值对的参数,需要用到注解@MatrixVariable,简单看下这个注解的几个属性:

name:这个很简单,matrix变量的名称
value:和name功能一样,是name的别名
pathVar:如果需要进行消除歧义,可以设置该URI路径变量的名称
required:是否必须,默认是true
defaultValue:默认值

3 简单分析

默认情况下 @MatrixVariable是不支持解析URL带分号的,设置URL中的分号";"内容从请求URI中剥离

* Set if ";" (semicolon) content should be stripped from the request URI. * <p>Default is "true". public void setRemoveSemicolonContent(boolean removeSemicolonContent) { this.removeSemicolonContent = removeSemicolonContent;

由于Springboot内置的Web框架是SpringMVC,所以我们得从Spring里面的Web Servlet入手,实现WebMvcConfigurer接口,重写configurePathMatch(PathMatchConfigurer configurer)方法

4.代码实现

@Configuration
public class SpringBootConfig implements WebMvcConfigurer {
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        UrlPathHelper urlPathHelper = new UrlPathHelper();
        urlPathHelper.setRemoveSemicolonContent(false);
        configurer.setUrlPathHelper(urlPathHelper);

Controller代码

@RequestMapping("/getInfo/{params}")
public void getInfo(@MatrixVariable Map<String, Object> param) {
    System.out.println(param);

5.测试结果

以下四种测试情况:

  • //localhost:8080/getInfo/name=root;pwd=123456;
  • //localhost:8080/getInfo/name=root;pwd=123456;pwd=234567;
  • //localhost:8080/getInfo/name=root;pwd=123456;pwd=234567