SpringBoot常用参数使用注解

常用参数注解使用

1、注解方式

@RequestParam

比如我们要获取请求参数的时候为了方便 , 则:

@RequestMapping("/YSN1.jpg")
    public String hello(@RequestParam("username") String name){
        return "aaa";
    }

写一个参数可以用@RequestParam来标注,比如写一个@RequestParam("username")这个意思就是 从请求参数的位置 拿到username 并赋值给name我们方便后面使用

2、Servlet API

比如我们在测试期间需要给session里面放一点数据,可以传入:

@RequestMapping("/YSN1.jpg")
    public String hello(HttpSesion session){
        return "aaa";
    }

就可以在方法里操作session

3、复杂参数

我们还可以传入复杂参数。比如Map Model特别是Model

Model

我们想要给页面放一点数据,在页面进行一些显示:

@RequestMapping("/YSN1.jpg")
    public String hello(Model model){
        return "aaa";
    }

我们就可以把数据放在model里面,我们model里面的数据最终会放到rquest请求域中。我们页面可以拿到请求域中的数据

4、自定义对象参数

比如我们传了一个Person:

@RequestMapping("/YSN1.jpg")
    public String hello(Person person){
        return "aaa";
    }

这样我们所有的提交过来的请求参数(或者是我们请求体里的k-v)全部会封装到我们Person对象里面来方便我们日常使用

测试一下

1、@PathVariable(路径变量)

<ul>
            <li>@PathVariable(路径变量)</li>
            <li>@RequestHeader(获取请求头)</li>
            <li>@RequestParam(获取请求参数)</li>
            <li>@CookieValue(获取Cookie值)</li>
            <li>@RequestBody(获取请求体)</li>
            <li>@MatrixVariable(矩阵变量)</li>
        </ul>

新建一个ParameterTestController.java

我们写一个方法返回Map<String,Object>(写给页面)

比如我们获取一个汽车信息(getCar()),建议使用Rest风格

如果我们想要获取id为1的信息可以:

@GetMapping("/car?id=1")		//这是发请求不是映射
//这样不方便建议:
@GetMapping("/car/{路径变量}")	//将来我们浏览器给我们发/car/1

就可以这么来写

@GetMapping("/car")
    public Map<String,Object> getCar(@PathVariable("id") Integer id){
        return null;
    }

那形参中的id从哪来呢?它是获取路径变量的值(@PathVariable("id")),按照路径上的变量自动变化

我们点进@PathVariable:

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PathVariable {

	@AliasFor("name")
	String value() default "";

	@AliasFor("value")
	String name() default "";

	boolean required() default true;

它是这么来说If the method parameter is Map<String, String> (java.util.Map)(如果这个参数的位值是一个Map)它会将所有的路径变量的k-v都会放进Map里所以可以这么写:

@GetMapping("/car/{id}/owner/{username}")
    public Map<String,Object> getCar1(@PathVariable Integer id,
                                      @PathVariable String username,
                                      @PathVariable Map<String,Object> pv){
        Map<String,Object> map1 = new HashMap<>();
        map1.put("id",id);
        map1.put("username",username);
        map1.put("pv",pv);
        return map1;
    }

我们这除了告诉它(@PathVariable)获取路径变量中谁的值(id)外的值,我们可以把所有的路径变量的k-v提取出来。 这就是路径变量,我们路径上的位值可以被动态替换

2、@RequestHeader(获取请求头)

每一次发请求我们都会发现: 我们请求都会带很多请求头 为了方便获取期间我们请求头在未来可能经常有用,比如在这请求头里面获取我们请求来源于是哪发的(Host),包括我们获取它的整个浏览器信息(User-Agent0);我就可以这么来做:

@GetMapping("/car/{id}/owner/{username}")
public Map<String,Object> getCar2(@PathVariable Integer id,
                                  @PathVariable String username,
                                  @PathVariable Map<String,Object> pv,
                                  @RequestHeader("User-Agent") String userAgent){
    Map<String,Object> map1 = new HashMap<>();
    map1.put("id",id);
    map1.put("username",username);
    map1.put("pv",pv);
    return map1;
}

@RequestHeader("User-Agent"):这是获取User-Agent一个请求头,我们请求头注解:

public @interface RequestHeader {

   @AliasFor("name")
   String value() default "";

   @AliasFor("value")
   String name() default "";

   boolean required() default true;

   String defaultValue() default ValueConstants.DEFAULT_NONE;

}

人家说这个请求头还可以传递成一个参数(Map)或(MultiValueMap)或者叫HttpHeaders(能帮你拿到所有的请求头)

传一个Map,值必须是String,String

@GetMapping("/car/{id}/owner/{username}")
public Map<String,Object> getCar2(@PathVariable Integer id,
                                  @PathVariable String username,
                                  @PathVariable Map<String,Object> pv,
                                  @RequestHeader("User-Agent") String userAgent,
                                  @RequestHeader Map<String,String> header){
    Map<String,Object> map1 = new HashMap<>();
    map1.put("id",id);
    map1.put("username",username);
    map1.put("pv",pv);
    map1.put("userAgent",userAgent);
    map1.put("header",header);
    return map1;
}

("")就是只拿某一个;不带就是拿所有。

同理我们可以测试一下多个:

3、@RequestParam(获取请求参数)

我们还可以用RequestParam获取请求参数,我们发请求的时候带上参数,我们随便写几个:

<a href="/car/1/owner/wo?age=18&inters=basketball">点击</a>

有一个属性多个值我们可以:

<a href="/car/1/owner/wo?age=18&inters=basketball&inters=game">点击</a>

我想要获取ageinters的值我们可以:

首先age是一个Integer我们可以@RequestParam("age") Integer age;

我们感兴趣的东西是List(集合)同样的可以@RequestParam("")获取我们的请求参数

@GetMapping("/car/{id}/owner/{username}")
public Map<String,Object> getCar2(@PathVariable Integer id,
                                  @PathVariable String username,
                                  @PathVariable Map<String,Object> pv,
                                  @RequestParam("age") Integer age,
                                  @RequestParam("inters") List<String> insters){
    Map<String,Object> map1 = new HashMap<>();
    map1.put("id",id);
    map1.put("username",username);
    map1.put("pv",pv);
    return map1;
}

包括@RequestParam:

public @interface RequestParam {

	@AliasFor("name")
	String value() default "";

	@AliasFor("value")
	String name() default "";

	boolean required() default true;

	String defaultValue() default ValueConstants.DEFAULT_NONE;

}

也说:你也可以来写一个Map,相当于它帮你把你所有请求参数的值都封装到了Map里面,所以当我想批量把我们请求所有的请求参数的值都拿过来的时候

@GetMapping("/car/{id}/owner/{username}")
public Map<String,Object> getCar2(@PathVariable Integer id,
                                  @PathVariable String username,
                                  @PathVariable Map<String,Object> pv,
                                  @RequestParam("age") Integer age,
                                  @RequestParam("inters") List<String> insters,
                                  @RequestParam Map<String,String> params){
    Map<String,Object> map1 = new HashMap<>();
    map1.put("age",age);
   	map1.put("insters",insters);
    map1.put("params",params);
    return map1;
}
{"params":{"age":"18","inters":"basketball"},"age":18,"insters":["basketball","game"]}

4、@CookieValue(获取Cookie值)

如果我们想要获取某个Cookie的值假如我们要获取"Idea"这个值:

我们要获取某一个Cookie的值

@GetMapping("/car/{id}/owner/{username}")
public Map<String,Object> getCar2(@PathVariable Integer id,
                                  @PathVariable String username,
                                  @CookieValue("Idea") String cookie){
    Map<String,Object> map = new HashMap<>();

    map.put("id",id);
    map.put("username",username);
    map.put("cookie",cookie);
    return map;
}

我们的CookieValue可以申明成Cookie:

/**
 * Annotation to indicate that a method parameter is bound to an HTTP cookie.
 *
 * <p>The method parameter may be declared as type {@link javax.servlet.http.Cookie}
 * or as cookie value type (String, int, etc.).
 *
 * <p>Note that with spring-webmvc 5.3.x and earlier, the cookie value is URL
 * decoded. This will be changed in 6.0 but in the meantime, applications can
 * also declare parameters of type {@link javax.servlet.http.Cookie} to access
 * the raw value.
 *
 * @author Juergen Hoeller
 * @author Sam Brannen
 * @since 3.0
 * @see RequestMapping
 * @see RequestParam
 * @see RequestHeader
 * @see org.springframework.web.bind.annotation.RequestMapping
 */
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CookieValue {

这样会把我们指定的Cookie的所所有信息全拿过来

5、@RequestBody(获取请求体)

也就是说只有我们POST请求才有请求体; 比如表单提交,里面有非常多的k-v可以把它整个表单里面的数据,那我们就可以写一个:

首先在index.html里面准备一个表单:

<form action="/save" method="post">
            <p1>测试@RequestBody获取数据</p1>
            用户名<input type="text" name="userName" /><br />
            密码<input type="text" name="email" /><br />
            <input type="submit" value="提交" />
        </form>

你发/save请求, 会给你提交userNameemail请求,所以@PostMapping("/save")处理的请求是/save。把俩个内容拿来String conent(表单的内容)使用一个注解@RequestBody String conent相当于把请求体的数据拿过来最终return map;

@PostMapping("/save")
public Map<String , Object> postMethod(@RequestBody String content){
    Map<String , Object> map = new HashMap<>();

    map.put("content",content);

    return map;
}

提交的时候我们Request请求有一个Form Data(表单数据)原本就是userName=hj&Email=123

所以我们能 获取到原本表单的信息

6、@RequestAttribute(获取request域属性)(重要)

它是来帮我们获取Request域中保存的属性。而我们在Requset域中设置属性,我们是来用页面转发的时候可以取出当前请求的数据。

这个请求特殊,专门写一个Controller来测试我们要进行页面跳转的测试

虽然还没有进行页面开发,但我们不应该返回json数据,所以我们写一个额外的RequestController

@Controller  //普通的Controller,它只是我们的一个控制器
public class RequestController {
    //如果是控制器我们默认方法的返回时进行页面跳转的
    public String goToPage(){}
}

比如我们要去一个goToPage页面;我们去页面之前来为方法发送一个@GetMapping()的请求,我们给它去一个页面,之歌页面就叫success页(return "success";)

因为我们现在没有引入模板引擎所以不能进行页面开发,就来模拟一下:所以我们return "forward:/success";(forward转发)转发到当前项目下的success请求取出请求页的数据,我们把public String success(){}的数据一返回写给浏览器就行了,使用@ResponseBody

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller  //普通的Controller,它只是我们的一个控制器
public class RequestController {
    //如果是控制器我们默认方法的返回时进行页面跳转的

    @GetMapping("/goto")
    public String goToPage(){
        return "forward:/success"; //转发到    /success请求
    }

    @ResponseBody
    @GetMapping("/success")
    public String success(){
        return null;
    }
}

我们先发/goto请求,然后它跳到success,success取出请求域中的数据,我现在想在请求域中放一个数据(HttpServletRequest request)我们把原生的Servlet请求拿到:

@GetMapping("/goto")
public String goToPage(HttpServletRequest request){
    request.setAttribute("msg","成功了");
    return "forward:/success"; //转发到    /success请求
}

由于我们/goto请求会转发到success所以我们来到success就是我们来的下一个请求,下一个请求为了方便能取出这个msg可以:

  • 1、@RequestAttribute("msg") String msg请求域中属性的方式取出msg。所以我们可以取出这个请求域中所有的东西我们都可以@RequestAttribute

    @ResponseBody
    @GetMapping("/success")
    public String success(@RequestAttribute("msg") String msg,
                          @RequestAttribute("code") Integer code){
        return null;
    }
    
  • 2、第二个获取办法是:HttpServletRequest request把原生的Servlet请求拿过来,因为是转发相当于:/gto转到/success是同一个请求,所以也可以调用代码的方式(request.getAttribute("msg");)按照k-v拿过来

为了打印方便我们还是使用Map的方式

我们可以去@RequestAttribute看一下

/**
 * Annotation to bind a method parameter to a request attribute.
 *
 * <p>The main motivation is to provide convenient access to request attributes
 * from a controller method with an optional/required check and a cast to the
 * target method parameter type.
 *
 * @author Rossen Stoyanchev
 * @since 4.3
 * @see RequestMapping
 * @see SessionAttribute
 */
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestAttribute {...}

a request attribute:说明RequestAttribute就是获取我们请求域中的值

@GetMapping("/goto")
    public String goToPage(HttpServletRequest request){
        request.setAttribute("msg","成功了");
        request.setAttribute("code",200);
        return "forward:/success"; //转发到    /success请求
    }

    @ResponseBody
    @GetMapping("/success")
    public Map success(@RequestAttribute("msg") String msg,
                       @RequestAttribute("code") Integer code,
                       HttpServletRequest request){
        Object msg1 = request.getAttribute("msg");

        Map<String,Object> map = new HashMap<>();
        map.put("reqMethod_msg",msg1);
        map.put("annotation_msg",msg);
        return map;
    }

我们来测试一下我们的/goto请求, 能不能获取到我们请求域中放的值

{"reqMethod_msg":"成功了","annotation_msg":"成功了"}

7、@MatrixVariable(矩阵变量)(重要)

我们来看它怎么用

什么是矩阵变量?我们看它怎么用

首先矩阵变量

/cars/{path}?xxx=xxx&xxx=xxx  query 查询字符串。@RequestParam

矩阵变量应绑定在路径变量中,整个路径变量我们可以这么来写:

/cars/{path;low=34;brand=byd,audi,yd}

我们来找所有销售的汽车(cars)价格是大于34W(low=34)并且品牌在这些里面的(brand=byd,audi,yd相当于我给它带了些成员条件)。而我们这种以;的这种写法我们把它称为矩阵变量

有一个面试题:页面开发如果cookie被禁用了,session里面的内容怎么使用

现在牵制到一个原理就是cookie session

我们给session里面保存了一个东西(session.set(a,b))  -->  因为我们每一个人每一个session都有一个sessionID(jsesionid)  --> 这个jsesionid会保存在cookie里面(每次发请求就会携带)

cookie没禁用以前 , **每次发请求,coolie会带上jsesionid,服务器按照jsesionid找到sesion对象,在调用sesion的get()方法就能找到我们sesion里面的内容 **

我们cookie被禁了以后,jsessionid因为存在cookie里面所以jsesionid就带不上了;jsesionid带不上了自然就在服务器里面找不到session对象,找不到session对象就获取不到里面的属性值。

我们还想要访问到可以这么来做:既然cookie带不了了我们就以矩阵变量的形式

/abc;jsession=xxx

我们把这种行为称为路径重写(url重写)我们通过url重写的方式我们可以解决cookie禁用的问题;相当于包我们把cookie的所有值使用我们矩阵变量的方式传递过来。

如果我们使用请求参数的方式进行传递就跟我们普通的请求参数没法区分了;而我们矩阵变量一般代表cookie的k-v

我们一传递后我们想要获取值怎么办?

<!--矩阵变量的路径写法分为这俩种-->
<a href="/cars/sell;low=34;brand=byd,audi,yd">@MatrixVariable(矩阵变量)</a>
<a href="/cars/sell;low=34;brand=byd;brand=audi;brand=yd">@MatrixVariable(矩阵变量)</a>

可以在ParameterTestController.java中做测试:

@GetMapping("/cars/sell") //只不过这个sell有很多的矩阵变量然不是请求参数
 public Map carsSell(){//为了方便以map的形式返回
     Map<String,Object> map = new HashMap<>();

     return map;
 }

首先我们看第一种方式:

<a href="/cars/sell;low=34;brand=byd,audi,yd">@MatrixVariable(矩阵变量)</a>

我们来获取矩阵变量里面的值:

首先我们来获取low的值(它是数字(Integer))

public Map carsSell(Integer low){}

然后有品牌的值,品牌还有多个

public Map carsSell(Integer low,List<String> brand){}

这俩个不是请求参数,是矩阵变量(@MatrixVariable):

public Map carsSell(@MatrixVariable("low") Integer low,
                     @MatrixVariable("brand") List<String> brand){}

我们来测试一下我们矩阵变量能不能使用:

public Map carsSell(@MatrixVariable("low") Integer low,
                     @MatrixVariable("brand") List<String> brand){
 ...
 map.put("low",low);
 map.put("brand",brand);
 ...
}
http://localhost:8080/cars/sell;low=34;brand=byd,audi,yd

请求没问题,但是页面报了个错, 错误是400,叫Required matrix variable 'low'(没有依赖于low),为什么没依赖?

注意点: springboot是默认禁用掉了矩阵变量的功能

所以我们要手动开启:

-要牵扯到定制化springboot底层,特别是springboot底层用的是springMVC相当于我们要定制化springMVC这个组件来完成这个功能

怎么定制化:来到springMVC的自动配置类:WebMvcAutoConfiguration;它在这个自动配置类里面有一个configurePathMatch()(配置我们路径映射),我们就要修改我们这个路径匹配的规则,因为路径匹配的规则里面,原理:

@Override
		public void configurePathMatch(PathMatchConfigurer configurer) {
			if (this.mvcProperties.getPathmatch()
					.getMatchingStrategy() == WebMvcProperties.MatchingStrategy.PATH_PATTERN_PARSER) {
				configurer.setPatternParser(new PathPatternParser());
			}
			configurer.setUseSuffixPatternMatch(this.mvcProperties.getPathmatch().isUseSuffixPattern());
			configurer.setUseRegisteredSuffixPatternMatch(
					this.mvcProperties.getPathmatch().isUseRegisteredSuffixPattern());
			this.dispatcherServletPath.ifAvailable((dispatcherPath) -> {
				String servletUrlMapping = dispatcherPath.getServletUrlMapping();
				if (servletUrlMapping.equals("/") && singleDispatcherServlet()) {
					UrlPathHelper urlPathHelper = new UrlPathHelper();
					urlPathHelper.setAlwaysUseFullPath(true);
					configurer.setUrlPathHelper(urlPathHelper);
				}
			});
		}

它里面有一个UrlPathHelper(url的路径帮助器),这个帮助器里面有一个属性叫private boolean removeSemicolonContent = true;(移除分号内容默认是true),这个removeSemicolonContent属性又是什么?来到它的setRemoveSemicolonContent()方法

/**
 * Set if ";" (semicolon) content should be stripped from the request URI.
 * <p>Default is "true".
 */
public void setRemoveSemicolonContent(boolean removeSemicolonContent) {
   checkReadOnly();
   this.removeSemicolonContent = removeSemicolonContent;
}

如果我们分号内容要移除,它会把请求路径后面所有的东西就截掉了(相当于是忽略了路径变量)

**对路径的处理我们spingboot都是使用UrlPathHelper进行解析的而UrlPathHelper里面有一个自定义属性removeSemicolonContent就是用来支持矩阵变量的,翻译过来就是要不要移除分号内容 **

如何自定义,就要回到以前的springMVC自动配置:

想要实现自动配置说了可以使用三种方案:

  • 不用@EnableWebMvc注解。使用@Configuration+WebMvcConfigure自定义规则

    • 可以自定义拦截器、格式化器等等;但是不能加注解。相当于因为@Configuration代表我们这个东西是容器中的一个组件,只要容器中有一个WebMvcConfigurer这个组件,然后你区定制化就行了

    • /**
       * Defines callback methods to customize the Java-based configuration for
       * Spring MVC enabled via {@code @EnableWebMvc}.
       *
       * <p>{@code @EnableWebMvc}-annotated configuration classes may implement
       * this interface to be called back and given a chance to customize the
       * default configuration.
       *
       * @author Rossen Stoyanchev
       * @author Keith Donald
       * @author David Syer
       * @since 3.1
       */
      public interface WebMvcConfigurer {}
      

      我们发现它其实是一个接口这个接口里面定义了一个方法:

      default void configurePathMatch(PathMatchConfigurer configurer) {}
      

      而我们WebMvcAutoConfiguration的时候,它给容器中(@Configuration)自动配置了这个类(WebMvcAutoConfigurationAdapter)这个类也是实现了WebMvcConfigurer这个接口,它在定义我们整个的路径映射规则的时候这个UrlPathHelper用色是默认的。默认是移除内容,所以我们只要放一个我们的WebMvcConfigurer

  • 声明WebMvcRegistrations改变默认底层组件

  • 使用@EnableWebMvc+@Configuration+DelegatingWebMvcConfiguration全面接管SpringMVC

我们想定义就俩种写法:

  • 1、给容器中放一个WebMvcConfigurer组件就行了

    //我们使用@Bean的方式给容器中放上我们的WebMvcConfigurer类型的组件
    

    我们就给容器放一个WebMvcConfigurer(返回值类型)

    我直接new一个接口,因为接口有默认实现,所以我们就修改一个configurePathMatch()方法。

    然后同样

    @Bean
    public WebMvcConfigurer webMvcConfigurer(){
        return new WebMvcConfigurer() {
            @Override
            public void configurePathMatch(PathMatchConfigurer configurer) {
                UrlPathHelper urlPathHelper = new UrlPathHelper();
                urlPathHelper.setRemoveSemicolonContent(false);
                configurer.setUrlPathHelper(urlPathHelper);
            }
        };
    }
    
  • 2、我们本身就是写在

    @Configuration(proxyBeanMethods = false)
    public class WebConfig {}
    

    这本身就是一个配置类我们让这个配置类实现WebMvcConfigurer

    @Configuration(proxyBeanMethods = false)
    public class WebConfig implements WebMvcConfigurer {}
    

    然后又由于我们JDK8有我们接口的默认实现

default void configurePathMatch(PathMatchConfigurer configurer) {}

所以我们无需将接口每一个接口都实现了,我们只需要修改我们要修改的方法:重写一个路径映射规则

@Configuration(proxyBeanMethods = false)
public class WebConfig implements WebMvcConfigurer {

    @Bean
    public HiddenHttpMethodFilter hiddenHttpMethodFilter(){
        HiddenHttpMethodFilter methodFilter = new HiddenHttpMethodFilter();
        methodFilter.setMethodParam("_m");
        return methodFilter;
    }

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        UrlPathHelper urlPathHelper = new UrlPathHelper();
        configurer.setUrlPathHelper(urlPathHelper);//改写url的路径帮助器,因为原来的规则是禁用掉这个规则的
    }

来到路径帮助器的方法:Ctrl+F12你就会发现这个方法有很多功能,比如:

  • 给我解码矩阵变量的decodeMatrixVariables()
  • 解码路径变量的decodePathVaruable()
  • 解码请求字符串decodeRequestString()

我们帮助器已经设定进去(configurer.setUrlPathHelper(urlPathHelper);)了,但是要在中间加一个最重要的一点:

//不移除;后面的内容.矩阵变量功能就可以生效
urlPathHelper.setRemoveSemicolonContent(false);//把RemoveSemicolonContent设置为false

因为默认是移除;后面的内容


这样我们矩阵变量就生效了

http://localhost:8080/cars/sell;low=34;brand=byd,audi,yd

变成了There was an unexpected error (type=Not Found, status=404).我们请求找不到,找不到 原因是(一定要记住:我们这个矩阵变量是要绑定在路径变量中的)所以我们这个sell不能直接写sell,要写成路径变量的表示法(/cars{path})这个路径是什么,然后在路径变量里面绑定了矩阵变量;而且我们路径是什么我们也可以拿到我们路径的内容

@GetMapping("/cars/{path}") //只不过这个sell有很多的矩阵变量然不是请求参数
public Map carsSell(@MatrixVariable("low") Integer low,
                    @MatrixVariable("brand") List<String> brand,
                    @PathVariable("path") String path){//为了方便以map的形式返回
    Map<String,Object> map = new HashMap<>();

    map.put("low",low);
    map.put("brand",brand);
    map.put("path",path);

    return map;
}

真正的访问路径它是把后面的分号也算成访问路径的一部分,还是真正的访问路径是/sell这一块

{"path":"sell","low":34,"brand":["byd","audi","yd"]}

我们获取到的路径就是sell路径中的矩阵变量的内容我们也获取到了("low":34)

<a href="/boss/1;age=18/2;age=19">@MatrixVariable(矩阵变量)/boos/{bossId}/{empId}</a>

如果遇到了这种麻烦事:我们有个矩阵变量有俩个相同的值(age):

//首先以第一路径变量 /1;ahe18  相当于 /{bossId}
//第二个路径变量 /2;age=19		是员工的id	/{empId}
//然后每一个路径变量中有相同矩阵变量的名字
//先获取我们age值  Integer bossAge  (@MatrixVariable("age") Integer bossAge)如果我这么来写那下面获取员工的写的age(@MatrixVariable("age") Integer empAge)我们最终是要一 一对应所以我们这种怎么写
//  /boss/1;age=18/2;age=19
    @GetMapping("/boss/{bossId}/{empId}")
    public Map boss(@MatrixVariable("age") Integer bossAge,
                    @MatrixVariable("age") Integer empAge){
        Map<String,Object> map = new HashMap<>();

        return map;
    }

@MatrixVariable里面有一个PathVar(相当于路径的变量)我们可以来指定我们这个矩阵变量@MatrixVariable("age") Integer bossAge我们获取值(vale="age"),它是获取哪个路径变量下的(pathVar="bossId")第二个同理

//  /boss/1;age=18/2;age=19
    @GetMapping("/boss/{bossId}/{empId}")
    public Map boss(@MatrixVariable(value = "age",pathVar = "bossId") Integer bossAge,
                    @MatrixVariable(value = "age",pathVar = "empId") Integer empAge){
        Map<String,Object> map = new HashMap<>();
        map.put("bossAge",bossAge);
        map.put("empAge",empAge);
        return map;
    }
{"bossAge":18,"empAge":19}

矩阵变量必须有url路径变量才能被解析


在springMVC底层的一个组件叫UrlPathHelper(路径帮助器)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

结城明日奈是我老婆

支持一下一直热爱程序的菜鸟吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值