ZetCode

Spring @MatrixVariable 教程

最后修改于 2023 年 10 月 18 日

Spring @MatrixVariable 教程展示了如何使用 @MatrixVariable 解析 URL 参数。

Spring 是一个流行的 Java 应用程序框架,用于创建企业级应用程序。

@MatrixVariable

@MatrixVariable 用于解析路径段内的名称-值对,并将它们绑定到方法参数。多个对之间用分号分隔。必须先启用矩阵变量。

Spring @MatrixVariable 示例

下面的应用程序解析 URL 路径段中的名称-值对。

pom.xml
src
├───main
│   ├───java
│   │   └───com
│   │       └───zetcode
│   │           ├───config
│   │           │       MyWebInitializer.java
│   │           │       WebConfig.java
│   │           └───controller
│   │                   MyController.java
│   ├───resources
│   └───webapp
│           index.html
└───test
    └───java

这是项目结构。

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
            http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zetcode</groupId>
    <artifactId>matrixvariableex</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <spring-version>5.3.23</spring-version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring-version}</version>
        </dependency>

        </dependencies>

    <build>
        <plugins>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.3.2</version>
            </plugin>

            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>9.4.49.v20220914</version>
            </plugin>

        </plugins>
    </build>
</project>

pom.xml 文件中,我们有项目依赖项。

com/zetcode/config/MyWebInitializer.java
package com.zetcode.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.FrameworkServlet;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

@Configuration
public class MyWebInitializer extends
        AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return null;
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        
        return new Class[]{WebConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        
        return new String[]{"/"};
    }
}

MyWebInitializer 初始化 Spring Web 应用程序。它包含一个配置类:WebConfig

com/zetcode/config/WebConfig.java
package com.zetcode.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.util.UrlPathHelper;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.zetcode"})
public class WebConfig implements WebMvcConfigurer {

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

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}

WebConfig 配置 Spring Web 应用程序。

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

在这里我们启用了矩阵变量。

com/zetcode/controller/MyController.java
package com.zetcode.controller;

import org.springframework.http.MediaType;
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.RestController;

import java.util.Map;

@RestController
public class MyController {

    @GetMapping(value = "/user/{first}/{last}",
            produces = MediaType.TEXT_PLAIN_VALUE)
    public String handler1(@MatrixVariable("first") String first,
                       @MatrixVariable("last") String last) {

        return String.format("Hello %s %s", first, last);
    }

    @GetMapping(value = "/data/{user:.*}",
            produces = MediaType.TEXT_PLAIN_VALUE)
    public String handler2(@MatrixVariable Map<String, String> data) {

        return String.format("Id: %s\nFirst name: %s\nLast Name: %s\nEmail: %s\n",
                data.get("id"), data.get("first"), data.get("last"), data.get("email"));
    }

    @GetMapping(value = "/geo/{continent}",
            produces = MediaType.TEXT_PLAIN_VALUE)
    public String handler3(@PathVariable("continent") String continent,
                         @MatrixVariable("country") String country,
                         @MatrixVariable("capital") String capital) {

        return String.format("Continent: %s\nCountry: %s\nCapital: %s\n",
                continent, country, capital);
    }
}

MyController 包含请求路径到处理方法的映射。

@GetMapping(value = "/user/{first}/{last}",
        produces = MediaType.TEXT_PLAIN_VALUE)
public String handler1(@MatrixVariable("first") String first,
                    @MatrixVariable("last") String last) {

    return String.format("Hello %s %s", first, last);
}

在这里我们使用 @MatrixVariable 将多个矩阵变量绑定到方法参数。

@GetMapping(value = "/data/{user:.*}",
        produces = MediaType.TEXT_PLAIN_VALUE)
public String handler2(@MatrixVariable Map<String, String> data) {

    return String.format("Id: %s\nFirst name: %s\nLast Name: %s\nEmail: %s\n",
            data.get("id"), data.get("first"), data.get("last"), data.get("email"));
}

在这里我们将多个名称-值对映射到一个 Map。

@GetMapping(value = "/geo/{continent}",
        produces = MediaType.TEXT_PLAIN_VALUE)
public String handler3(@PathVariable("continent") String continent,
                        @MatrixVariable("country") String country,
                        @MatrixVariable("capital") String capital) {

    return String.format("Continent: %s\nCountry: %s\nCapital: %s\n",
            continent, country, capital);
}

在第三种情况下,我们将 @MatrixVariable@PathVariable 结合使用。

webapp/index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Home page</title>
</head>
<body>

<p>
    <a href="https://:8080/user/first=John/last=Doe">Greet user</a>
</p>

<p>
    <a href="https://:8080/data/id=1;first=John;last=Doe;email=johndoe@gmail.com">Show user data</a>
</p>

<p>
    <a href="https://:8080/geo/Europe;country=Slovakia;capital=Bratislava">Show country info</a>
</p>

</body>
</html>

这是主页。我们有三个包含名称-值对的链接,这些链接通过 @MatrixVariable 注解进行解析。

在本文中,我们使用 @MatrixVariable 来解析路径段上的名称-值对,并将它们绑定到方法参数。

作者

我叫 Jan Bodnar,我是一名热情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直在撰写编程文章。迄今为止,我已撰写了 1,400 多篇文章和 8 本电子书。我在教学编程方面拥有超过十年的经验。

列出 所有 Spring 教程