Spring 註解面面通 之 @MatrixVariable

securitit發表於2020-12-05

  @MatrixVariable用來將請求URI矩陣變數對映到控制器處理方法的引數中。

  矩陣引數

  URL的一般語法是:protocol://hostname[:port]/path[;parameters][?query]#fragment,其中[;parameter]即常被稱為矩陣引數。

  矩陣引數[;parameter]一般用來描述特定路徑元素,而查詢字串[?query]一般用來描述整個URL。在對多個級別的資源和子資源進行基於REST規範的複雜設計時,用處會非常大。

  註解解析

  ① value

    繫結的引數名稱,引數值為String型別。

  ② name

​    繫結的引數名稱,引數值為String型別。namevalue可以同時使用,但兩者的值需一致,否則會出現錯誤。

attribute 'name' and its alias 'value' are present with values of [XXX] and [XXX], but only one is permitted

  ③ pathVar

​    矩陣變數所在的路徑變數的名稱,若URL中存在多個相同的路徑,則需要消除歧義。

  ④ required

    路徑中是否必須包含指定的值,預設值為true

    requiredtrue時,如果路徑中缺少指定的值,則會丟擲異常。

    requiredtrue時,如果路徑中缺少指定的值,則會返回null

  ⑤ defaultValue

    矩陣變數繫結失敗時的預設值,指定預設值後,會隱式的將required設定為false

  註解示例

  1)Controller,用來演示@MatrixVariable使用方法。

package com.arhorchin.securitit.webannotations;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.MatrixVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;

/**
 * @author Securitit.
 * @note 演示@MatrixVariable使用方法.
 */
@Controller
@RequestMapping("/WebAnnotations")
public class MatrixVariableController {

    /**
     * logger.
     */
    private Logger logger = LoggerFactory.getLogger(MatrixVariableController.class);

    /**
     * 跳轉頁面.
     */
    @RequestMapping(
            value = "/MatrixVariable.html",
            method = RequestMethod.GET)
    public ModelAndView matrixVariableHtml(HttpServletRequest req, HttpServletResponse res, ModelMap modelMap)
            throws Exception {
        return new ModelAndView("webannotations/MatrixVariable", modelMap);
    }

    /**
     * 以Map解析矩陣引數.
     */
    @ResponseBody
    @RequestMapping(
            value = "/{Province}/{City}/MatrixVariableMap.do",
            method = RequestMethod.GET)
    public String matrixVariableMap(@MatrixVariable Map<String, String> matrixVariableMap) throws Exception {
        logger.info("Current value of MatrixVariable is " + JSON.toJSONString(matrixVariableMap));
        return "Current value of MatrixVariable is " + JSON.toJSONString(matrixVariableMap);
    }

    /**
     * 以單鍵值形式解析矩陣引數.
     */
    @ResponseBody
    @RequestMapping(
            value = "/{Province}/{City}/MatrixVariableSingle.do",
            method = RequestMethod.GET)
    public String matrixVariableSingle(@MatrixVariable(
            pathVar = "Province") Map<String, String> matrixVariableMap) throws Exception {
        logger.info("Current value of MatrixVariable [Province] is " + JSON.toJSONString(matrixVariableMap));
        return "Current value of MatrixVariable [Province] is " + JSON.toJSONString(matrixVariableMap);
    }

    /**
     * 以單鍵值形式解析矩陣引數.
     */
    @ResponseBody
    @RequestMapping(
            value = "/{Province}/{City}/MatrixVariableSingleVal.do",
            method = RequestMethod.GET)
    public String matrixVariableSingleVal(@MatrixVariable(
            value = "sex",
            pathVar = "Province") String sexVal) throws Exception {
        logger.info("Current value of MatrixVariable [Province-sex] is " + sexVal);
        return "Current value of MatrixVariable [Province-sex] is " + sexVal;
    }

    /**
     * 以單鍵值形式解析矩陣引數.
     */
    @ResponseBody
    @RequestMapping(
            value = "/MatrixVariableSingleRequiredTrue/{Province}",
            method = RequestMethod.GET)
    public String matrixVariableSingleRequiredTrue(@MatrixVariable(
            value = "vCur",
            pathVar = "Province",
            required = true) Map<String, String> matrixVariableMap) throws Exception {
        logger.info("Current value of MatrixVariable is " + JSON.toJSONString(matrixVariableMap));
        return "Current value of MatrixVariable is " + JSON.toJSONString(matrixVariableMap);
    }

    /**
     * 以單鍵值形式解析矩陣引數.
     */
    @ResponseBody
    @RequestMapping(
            value = "/MatrixVariableSingleRequiredFalse/{Province}",
            method = RequestMethod.GET)
    public String matrixVariableSingleRequiredFalse(@MatrixVariable(
            value = "vCur",
            pathVar = "Province",
            required = false) Map<String, String> matrixVariableMap) throws Exception {
        logger.info("Current value of MatrixVariable is " + JSON.toJSONString(matrixVariableMap));
        return "Current value of MatrixVariable is " + JSON.toJSONString(matrixVariableMap);
    }

}

  2)html,用來演示MatrixVariableController示例。

<!doctype html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<meta name="Author" content="LiNing">
		<meta name="Keywords" content="-">
		<meta name="Description" content="LiNing @MatrixVariable 測試頁面">
		<title>@MatrixVariable 測試頁面</title>
	</head>
	<body>
		<a href="http://localhost:9199/spring-annotations/WebAnnotations/LiNing;sex=male;age=30/DaLian;name=csdn;year=eight;/MatrixVariableMap.do" target="_blank">點選連結,@MatrixVariable進行引數繫結,後端以Map解析方法引數.</a>
		<br />
		<br />
		<a href="http://localhost:9199/spring-annotations/WebAnnotations/LiNing;sex=male;age=30/DaLian;name=csdn;year=eight;/MatrixVariableSingle.do" target="_blank">點選連結,@MatrixVariable進行引數繫結,後端指定pathVar,以單鍵值形式解析方法引數.</a>
		<br />
		<br />
		<a href="http://localhost:9199/spring-annotations/WebAnnotations/LiNing;sex=male;age=30/DaLian;name=csdn;year=eight;/MatrixVariableSingleVal.do" target="_blank">點選連結,@MatrixVariable進行引數繫結,後端指定value和pathVar,以單鍵值形式解析方法引數.</a>
		<br />
		<br />
		<a href="http://localhost:9199/spring-annotations/WebAnnotations/MatrixVariableSingleRequiredTrue/LiNing" target="_blank">點選連結,@MatrixVariable進行引數繫結,後端指定required=true,以單鍵值形式解析方法引數.</a>
		<br />
		<br />
		<a href="http://localhost:9199/spring-annotations/WebAnnotations/MatrixVariableSingleRequiredFalse/LiNing" target="_blank">點選連結,@MatrixVariable進行引數繫結,後端指定required=false,以單鍵值形式解析方法引數.</a>
	</body>
</html>

  3) 啟動服務,訪問http://localhost:9199/spring-annotations/WebAnnotations/MatrixVariable.html頁面。

在這裡插入圖片描述

  分別點選頁面中的連結,檢視@MatrixVariable對應的效果。

  ① 點選連結,@MatrixVariable進行引數繫結,後端以Map解析方法引數.

在這裡插入圖片描述

  ② 點選連結,@MatrixVariable進行引數繫結,後端指定pathVar,以單鍵值形式解析方法引數.

在這裡插入圖片描述

  ③ 點選連結,@MatrixVariable進行引數繫結,後端指定value和pathVar,以單鍵值形式解析方法引數.

在這裡插入圖片描述

  ④ 點選連結,@MatrixVariable進行引數繫結,後端指定required=true,以單鍵值形式解析方法引數.

在這裡插入圖片描述

  ⑤ 點選連結,@MatrixVariable進行引數繫結,後端指定required=false,以單鍵值形式解析方法引數.

在這裡插入圖片描述

  總結

  涉及到需要涉及負責的REST風格API時,@MatrixVariable是十分有用處的,可以在URL的路徑中針對特定路徑新增著重的描述,以便後端進行豐富的處理。

  若文中存在錯誤和不足,歡迎指正!

相關文章