首页 > 其他 > 详细

注解之@PathVariable

时间:2019-11-26 11:20:29      阅读:122      评论:0      收藏:0      [点我收藏+]

@PathVariable只支持一个属性value,类型是为String,代表绑定的属性名称。默认不传递时,绑定为同名的形参。 

用来便捷地提取URL中的动态参数。其英文注释如下:

Annotation which indicates that a method parameter should be bound to a URI template variable. Supported for {@link RequestMapping} annotated handler methods in Servlet environments.

应用时,在@RequestMapping请求路径中,将需要传递的参数用花括号{}括起来,然后,通过@PathVariable("参数名称")获取URL中对应的参数值。如果@PathVariable标明参数名称,则参数名称必须和URL中参数名称一致。

技术分享图片
@RequestMapping("/viewUser/{id}/{name}")
    public Map<String, Object> viewUser(@PathVariable("id") Integer idInt, @PathVariable Integer name) {
        System.out.println("@PathVariable中 请求参数 id = " + idInt);
        Map<String, Object> user = new HashMap<>();
        user.put("id", idInt);
        user.put("name", name);
        return user;
    }
    /**
     * @Title viewUser2
     * @Description @PathVariable未标注参数名称,则被注解参数名必须后URL中的一致
     * @date 2018-12-15 11:08
     */
    @RequestMapping("/owners/{ownerId}")
    public Map<String, Object> viewUser2(@PathVariable Integer ownerId) {
        System.out.println("@PathVariable中 请求参数 ownerId = " + ownerId);
        Map<String, Object> user = new HashMap<>();
        user.put("id", ownerId);
        user.put("name", "Lucy");
        return user;
    }
技术分享图片

URI 模板 “/owners/{ownerId}” 指定了一个名叫 ownerId的变量。当控制器处理这个请求时,ownerId的值被设置为从 URI 中解析出来。比如,当请求 /viewUser/100 进来时,100 就是 ownerId的值。 

参考文献:https://docs.spring.io/spring/docs/5.0.0.M1/spring-framework-reference/htmlsingle/#mvc-ann-requestmapping-uri-templates

 

 
分类: Spring

注解之@PathVariable

原文:https://www.cnblogs.com/chenchen127/p/11934071.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!