欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring 注解面面通 之 @MatrixVariable

程序员文章站 2022-03-14 18:41:27
...

  @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页面。

Spring 注解面面通 之 @MatrixVariable

  分别点击页面中的链接,查看@MatrixVariable对应的效果。

  ① 点击链接,@MatrixVariable进行参数绑定,后端以Map解析方法参数.

Spring 注解面面通 之 @MatrixVariable

  ② 点击链接,@MatrixVariable进行参数绑定,后端指定pathVar,以单键值形式解析方法参数.

Spring 注解面面通 之 @MatrixVariable

  ③ 点击链接,@MatrixVariable进行参数绑定,后端指定value和pathVar,以单键值形式解析方法参数.

Spring 注解面面通 之 @MatrixVariable

  ④ 点击链接,@MatrixVariable进行参数绑定,后端指定required=true,以单键值形式解析方法参数.

Spring 注解面面通 之 @MatrixVariable

  ⑤ 点击链接,@MatrixVariable进行参数绑定,后端指定required=false,以单键值形式解析方法参数.

Spring 注解面面通 之 @MatrixVariable

  总结

  涉及到需要涉及负责的REST风格API时,@MatrixVariable是十分有用处的,可以在URL的路径中针对特定路径添加着重的描述,以便后端进行丰富的处理。

  若文中存在错误和不足,欢迎指正!