【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中指定的属性名**保持一致即可:

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

相关推荐
用户8307196840824 天前
spring ai alibaba + nacos +mcp 实现mcp服务负载均衡调用实战
spring boot·spring·mcp
NE_STOP7 天前
springMVC-HTTP消息转换器与文件上传、下载、异常处理
spring
刀法如飞8 天前
一款Go语言Gin框架MVC脚手架,满足大部分场景
go·mvc·gin
JavaGuide8 天前
Claude Opus 4.6 真的用不起了!我换成了国产 M2.5,实测真香!!
java·spring·ai·claude code
玹外之音8 天前
Spring AI MCP 实战:将你的服务升级为 AI 可调用的智能工具
spring·ai编程
来一斤小鲜肉8 天前
Spring AI入门:第一个AI应用跑起来
spring·ai编程
NE_STOP8 天前
springMVC-常见视图组件与RESTFul编程风格
spring