Springboot use MatrixVariable comment

    The URI specification defines the URL in RFC 3986, it may include a path segment may pairs. Specification no corresponding term pair. General "URL path argument" can be applied, although more unique, "Matrix URI" is also often used and quite famous. In Spring MVC it ​​is to be variable matrix

    Matrix variables can appear in any path segment, each of the variables a matrix with a semicolon (;) apart. For example, /cars;color=red;year=2012" ." It may be a plurality of values separated by commas, such as color=red,green,blue" ", or write separately color=red;color=green;color=blue" ."

    If you want a URL contains a matrix variable, then the request URI template mapping mode must be used to represent these matrix variables. In this case, regardless of the matrix variable order, we are able to ensure that the request can correct match.

Springboot default is to not use the matrix variable binding parameters. WebMvcConfigurer need to override the method configurePathMatch.

@Configuration
public class WebConfig implements WebMvcConfigurer {

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

XML-based configuration

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

Write variable matrix controller

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";
    }
    
    /**
     * Matrix variables can set default values 
     * / 
    @GetMapping ( "/ Qucik Facts Pets / petId {}" )
     public String findPet ( 
            @MatrixVariable (required = to false , defaultValue = ". 1") int Q) 
    { 
        System.out.println ( "- -> Q of the Default value: "+ Q); 
        
        return " / examples / Targets / test2 " ; 
    } 
}

Guess you like

Origin www.cnblogs.com/deityjian/p/11621143.html