SpringBoot-请求处理@MatrixVariable

1,507 阅读2分钟

SpringBoot 如何接收请求矩阵变量的值?

引出

在页面开发中,如果cookie被禁用了, session 中的内容怎么使用?

问题

session 需要根据jsessionid 来找到具体是哪一个session 而jsessionid 要携带在cookie 中,如果cookie被禁用,服务器就不知道要找哪一个session了

解决办法

URL重写: /abc;jessionid=xxxxx 把Cookie 的值使用矩阵变量的方式进行传递

什么是矩阵变量

  • URL:/cars/sell;low=34;brand=byd,audi,yd
  • URL:/cars/sell;low=34;brand=byd;brand=audi,brand=yd
  • URL:/cars/1;age=20/2;age=10

矩阵变量是跟在请求里面的, 第一个是请求sell 携带的参数为low,brand,第三个请求是cars/1 参数age=20 和 cars/2 age=20

编写测试的类

@RestController  
public class MatrixVariableController {  
@GetMapping("/car/sell")  
public Map test(@MatrixVariable ("low")Integer low,@MatrixVariable("brand") List<String> brand){  
Map map=new HashMap();  
map.put("low",low);  
map.put("brand",brand);  
return map;  
}  
}

访问URL http://localhost:8080/car/sell;low=34;brand=byd,cdi,yd

image.png

原因分析

SpringBoot 默认禁用掉了 矩阵变量的用法 需要我们手动开启

代码分析

image.png

image.png

image.png

现在我们需要手动配置 将这个值设为false

使用@WebMvcConfigurer +@Configuration 自定义规则

第一种写法 在Myconfig类中 注册Bean

@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);  
}  
};  
}  
}

第二种写法 让我们的Myconfig 实现 WebMvcConfigurer 接口

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

再次访问 http://localhost:8080/car/sell;low=34;brand=byd,cdi,yd

image.png

错误原因

矩阵变量是要写在路径变量中 ,也就是说 我们的访问url 路径变量为"sell;low=34;brand=byd,cdi,yd"

修改Controller

@RestController  
public class MatrixVariableController {  
@GetMapping("/car/{path}")  
public Map test(@MatrixVariable ("low")Integer low, @MatrixVariable("brand") List<String> brand, @PathVariable("path")String path){  
Map map=new HashMap();  
map.put("low",low);  
map.put("brand",brand);  
map.put("path",path);  
return map;  
}  
}

访问http://localhost:8080/car/sell;low=34;brand=byd,cdi,yd

image.png

http://localhost:8080/car/sell;low=34;brand=byd,cdi,yd 这个链接已经解决了,那么这个链接怎么解决呢? <http://localhost:8080/boss/1;age=20/2;age=10

编写Corntoller

@RestController  
public class MatrixVariableController {  
@GetMapping("/boss/{a}/{b}")  
public Map test2(@MatrixVariable(value = "age",pathVar = "a") Integer boosAge,@MatrixVariable(value = "age",pathVar = "b") Integer empId){  
Map map=new HashMap();  
map.put("bossAge",boosAge);  
map.put("empid",empId);  
return map;  
}  
}

结果

image.png