首页 > 其他分享 >SpringMVC中注解@PathVariable的认识

SpringMVC中注解@PathVariable的认识

时间:2024-09-25 23:21:21浏览次数:3  
标签:web PathVariable SpringMVC import springframework org 注解 annotation

一、前言

@PathVariable是Spring MVC中的一个非常重要的注解,作用在于将URL中的模板变量(即路径变量)绑定到控制器方法的参数上。这一功能特别适用于处理RESTful风格的请求,使得开发者能够直接从URL中提取参数值,并将其传递给方法进行处理。通过使用@PathVariable注解,可以设计出更加灵活和动态的URL映射,同时简化参数传递的过程,提高代码的可读性和可维护性。

二、实战案例

1.基本使用

为使映射正确工作,捕获 URI 变量 {id} 的名称必须与 @PathVariable 成员参数id 相同。

package com.example.springbootdemo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @GetMapping("/test/{id}")
    public String test(@PathVariable Long id) {
        return "test->" + id;
    }
}

程序测试:

SpringMVC中注解@PathVariable的认识_@PathVariable

如果将参数名修改如下:@PathVariable Long key的话,由于URL路径中的变量和参数的变量不一致就会导致异常。

package com.example.springbootdemo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @GetMapping("/test/{id}")
    public String test(@PathVariable Long key) {
        return "test->" + key;
    }
}

程序运行:

SpringMVC中注解@PathVariable的认识_SpringMVC_02

SpringMVC中注解@PathVariable的认识_@PathVariable_03

所以,在这种情况下你参数的名称要与模板中的一样。

2.不同参数名

我们可以通过将参数传递给 @PathVariable 注解,显式访问捕获 URI 变量。我们在@PathVariable注解中指明参数名称。

package com.example.springbootdemo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @GetMapping("/test/{id}")
    public String test(@PathVariable("id") Long key) {
        return "test->" + key;
    }
}

程序运行:

SpringMVC中注解@PathVariable的认识_@PathVariable_04

通过指明路径参数名,这样就不会报错了。

3.类级别的路径变量

下面的示例展示了如何使用 @PathVariable 在类和方法级别访问URI 变量。

package com.example.springbootdemo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/test/{type}")
public class TestController {

    @GetMapping("/{id}")
    public String test(@PathVariable Integer type, @PathVariable("id") Long key) {
        return "type=>" + type + ",key=>" + key;
    }
}

程序运行:

SpringMVC中注解@PathVariable的认识_@PathVariable_05

这里的路径变量type与参数名一致所以不用指定名称。

4.多个URI变量

你也可以定义多个 @PathVariable 注解来访问捕获的 URI 变量。

package com.example.springbootdemo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @GetMapping("/test/{type}/{id}")
    public String test(@PathVariable Integer type, @PathVariable("id") Long key) {
        return "type=>" + type + ",key=>" + key;
    }
}

程序运行:

SpringMVC中注解@PathVariable的认识_@PathVariable_06

只要你想,只要不超过GET请求大小限制,你可以设置N多的路径参数。

5.Map接收路径变量

@PathVariable注解还支持Map类型

package com.example.springbootdemo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
public class TestController {

    @GetMapping("/test/{type}/{id}")
    public String test(@PathVariable Map<String, String> map) {
        Integer type = Integer.valueOf(map.get("type"));
        Integer id = Integer.valueOf(map.get("id"));
        return "type=>" + type + ",id=>" + id;
    }
}

程序运行:

SpringMVC中注解@PathVariable的认识_@PathVariable_07

6.正则路径变量

package com.example.springbootdemo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class TestController {

    @GetMapping("/test/{name:[a-z]+}")
    public String test(@PathVariable String name) {
        return name;
    }
}

程序运行:

SpringMVC中注解@PathVariable的认识_SpringMVC_08

该路径将只会匹配最后的name为a~z组合的字符。

SpringMVC中注解@PathVariable的认识_SpringMVC_09

7.可选的路径变量

默认情况下@PathVariable路径变量是必须,否则服务端将MethodArgumentTypeMismatchException异常。我们除了可以通过设置PathVariable注解的required属性为false外,还可以通过Optional类型接收值,如下示例:

package com.example.springbootdemo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;


@RestController
public class TestController {

    @GetMapping({"/test/{id}", "/tests/"})
    public Long test(@PathVariable Optional<Long> id) {
        return id.orElseGet(() -> -1L);
    }
}

匹配两个路径,没有id则返回-1。

程序运行:

SpringMVC中注解@PathVariable的认识_@PathVariable_10

SpringMVC中注解@PathVariable的认识_SpringMVC_11

三、总结

通过使用@PathVariable我们学习多种使用方式,展示其在实际开发中的灵活性和强大功能。


标签:web,PathVariable,SpringMVC,import,springframework,org,注解,annotation
From: https://blog.51cto.com/u_13312531/12112567

相关文章

  • SpringBoot注解大全(详细)
    1.@ActiveProfiles用来声明活动的profile–@ActiveProfiles(“prod”(这个prod定义在配置类中))@RunWith(SpringRunner.class)@SpringBootTest@ActiveProfiles("test")publicclassMyApplicationTests{@TestpublicvoidcontextLoads(){......
  • 注解的本质与工作原理
    一、注解的本质是什么?1.1注解的定义注解(Annotation)是Java5引入的一种元数据(Metadata)机制,用于在代码中添加额外的信息。注解本质上是一种特殊的接口,后续会由工具和框架在编译时、类加载时、或运行时进行处理,以实现特定的功能。1.2注解的分类注解可以分为三类:标准注解:Java......
  • 【SpringBoot】@Valid @Validated 注解校验时机实现原理
    1 前言上节我们看了【SpringBoot】@Validated@Valid参数校验概述以及使用方式,对于@Valid以及@Validated有了大概的认识,并也尝试了集中校验方式,那么本节我们重点看一下SpringBoot中@Valid@Validated的校验实现原理。2 准备工作客户类我还是用上节的那个类,然后我......
  • @Scheduled注解停止定时任务、@Scheduled设置定时任务不启用、springboot 配置Schedul
    文章目录一、关闭定时任务1.1、方法一:注释@EnableScheduling注解1.1.1、原理1.2、方法二:不加载ScheduledAnnotationBeanPostProcessor类1.3、方法三:注释@Scheduled注解1.4、方法四:设置@Scheduled注解cron时间不开启(推荐)1.4.1、原理在项目中我们可能会遇到这样一......
  • SpringBoot使用@Scheduled注解实现定时任务
    SpringBoot使用@Scheduled注解实现定时任务_springbootscheduled注解-CSDN博客 importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importorg.springframework.scheduling.annotation.EnableSched......
  • 编程式事务和注解式事务的区别
    优缺点在SpringBoot中,事务管理有两种主要方式:声明式事务管理和编程式事务管理。这两种方式各有特点,适用于不同的场景。分别为:Transactional注解实现事务PlatformTransactionManager类实现编程式事务声明式事务管理(@Transactional)定义:通过注解的方式将事务管理与业......
  • springmvc
    一、快速入门新建项目导入依赖在web.xml中添加前端控制器构建项目结构spring配置文件编写controller类注解解释@Controller注解继承于spring代表将类交给ioc容器,在使用时需要在spring.xml中配置包扫描@RequestMapping用于建立请求URL和处理请求方法之间的对......
  • jackson学习之五:JsonInclude注解
    本文是《jackson学习》系列第五篇,来熟悉一个常用的注解JsonInclude,该注解的仅在序列化操作时有用,用于控制方法、属性等是否应该被序列化;之所以用单独的一篇来写JsonInclude注解,是因为该注解的值有多种,每种都有不同效果,最好的学习方法就是编码实战;先对注解的所有取值做个简......
  • spring cxf 常用注解
    在Spring框架中,特别是当与ApacheCXF(一个流行的SOAP和RESTfulWeb服务框架)结合使用时,我们会遇到一系列的注解。以下是一些在Spring和CXF中常用的注解:Spring相关注解:@Component:用于定义一个bean,它会被Spring容器管理。通常与@Autowired一起使用以实现自动注入。@Service:专用于服务......
  • spring 常用注解
    Spring框架中的核心注解12@Component:用于类定义上,表明该类将被Spring容器作为组件管理。@Service:用于标注服务层的组件。@Repository:用于标注数据访问组件,即DAO组件。@Autowired:自动连接Bean之间的依赖关系。@Qualifier:指定注入Bean的名称。@Value:注入属性值。@Transactional......