Springboot使用MatrixVariable 注解

    根据 URI 规范 RFC 3986 中 URL 的定义,路径片段中可以可以包含键值对。规范中没对对应的术语。一般 “URL 路径参数” 可以被应用,尽管更加独特的 “矩阵 URI” 也经常被使用并且相当有名。在 Spring MVC 它被成为矩阵变量

    矩阵变量可以出现在任何路径片段中,每一个矩阵变量都用分号(;)隔开。比如 “/cars;color=red;year=2012”。多个值可以用逗号隔开,比如 “color=red,green,blue”,或者分开写 “color=red;color=green;color=blue”。

    如果你希望一个 URL 包含矩阵变量,那么请求映射模式必须用 URI 模板来表示这些矩阵变量。这样的话,不管矩阵变量顺序如何,都能够保证请求可以正确的匹配。

Springboot 默认是无法使用矩阵变量绑定参数的。需要覆盖WebMvcConfigurer中的configurePathMatch方法。

@Configuration
public class WebConfig implements WebMvcConfigurer {

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

基于XML的配置

<mvc:annotation-driven enable-matrix-variables="true" />

编写矩阵变量控制器

package com.techmap.examples.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.MatrixVariable;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/matrix")
public class MatrixController
{
    
    /**
     * 使用矩阵变量
     */
    @GetMapping("/owners/{ownerId}/pets/{petId}")
    public String findPet(
            @PathVariable String ownerId,
            @PathVariable String petId,
            @MatrixVariable(name = "q", pathVar = "ownerId") int q1,
            @MatrixVariable(name = "q", pathVar = "petId") int q2) 
    {
        System.out.println("--> ownerId : " + ownerId);
        System.out.println("--> petId : " + petId);
        System.out.println("--> q1 : " + q1);
        System.out.println("--> q2 : " + q2);
        
        return "/examples/targets/test1";
    }
    
    /**
     * 矩阵变量可以设置默认值
     */
    @GetMapping("/pets/{petId}")
    public String findPet(
            @MatrixVariable(required = false, defaultValue = "1") int q) 
    {
        System.out.println("--> Default value of q : " + q);
        
        return "/examples/targets/test2";
    }
}

猜你喜欢

转载自www.cnblogs.com/deityjian/p/11621143.html