【JavaEE】_Spring MVC项目获取URL中的参数

目录

[1. 单参数](#1. 单参数)

[2. 多参数](#2. 多参数)


1. 单参数

.java文件如下:

java 复制代码
package com.example.demo.controller;

import com.example.demo.Person;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RequestMapping("/Para")
@RestController
public class ParaController {
    @RequestMapping("/M9/{userId}")
    public String m9(@PathVariable Integer userId){
        return "userId: "+userId;
    }

}

运行启动类,使用postman构造HTTP请求,其中URL带有参数,构造完成后发送,详情如下:

注意URL的格式要与@RequestMapping注解的格式一致:

2. 多参数

.java文件如下:

java 复制代码
package com.example.demo.controller;

import com.example.demo.Person;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RequestMapping("/Para")
@RestController
public class ParaController {
    @RequestMapping("/M9/{userId}/{name}")
    public String m9(@PathVariable Integer userId,@PathVariable String name){
        return "userId: "+userId+"\n"
                +"name:"+name;
    }

}

运行启动类,使用postman构造请求,其中URL有2个参数,详情如下:

注意URL多参数时:

(1).java文件中,在函数参数部分,每一个参数都需要一个@PathVariable注解;

(2)请求的URL部分参数需要与.java文件中@RequestMapping注解中的格式保持一致;

(3)URL中的参数与后端的.java代码的对应是有顺序且个数严格匹配的,比如类型不匹配,参数顺序错误与少传与多传参数都会引起错误;

(4)若后端需对接收到的请求重命名,可以在@PathVariable注解中标明属性名:

java 复制代码
    @RequestMapping("/M9/{userId}/{name}")
    public String m9(@PathVariable Integer userId,@PathVariable("name") String username){
        return "userId: "+userId+"\n"
                +"username:"+username;
    }

只需保证**@RequestMapping中指定的URL格式中的属性名** 与**@PathVariable中指定的属性名**保持一致即可:

再次运行并发送请求可见:

相关推荐
专业程序开发源8 小时前
springboot欧缇蔓月子中心管理系统82697-计算机课程设计、毕业设计
java·spring boot·后端·python·spring·django·课程设计
小溪学编程10 小时前
将 Bean 放入 Spring 容器中的方式有哪些?
java·后端·spring
我命由我1234512 小时前
Python 开发 - Python 虚拟环境
运维·开发语言·后端·python·http·https·java-ee
Vegetable_xu12 小时前
Spring Bean 循环依赖:为什么有时能过、有时启动就挂
java·spring·mybatis
开开心心_Every16 小时前
免费压缩软件WinRAR无弹窗、广告干扰
java·开发语言·前端·spring·智能手机·word·winrar
YDS82916 小时前
Small Spring IOC篇:应用上下文实现和Bean的扩展
java·后端·spring
萧瑟余晖17 小时前
Spring Cloud分布式事务与链路追踪详解
分布式·spring·spring cloud
步行cgn19 小时前
Spring MVC POST 请求乱码:原因与完整解决方案
java·spring·mvc
斌糖雪梨1 天前
spring auth 核心流程详解
java·后端·spring
唠点键盘之外的1 天前
29 切片的权限隔离(实战篇):Milvus + Spring AI,从 0 搭一条带权限过滤的检索链路
人工智能·spring·milvus