[Spring MVC] Controller接受参数问题,针对@RequestParam
用实体类接收
-
测试实体类
public class TestEntity { private String name; private Integer age; // getter setter toString }
-
Controller代码
@PostMapping("/testSend") public void testSend(TestEntity testEntity) { System.out.println(testEntity); }
-
form-data 测试
后台打印结果:TestEntity
-
x-www-form-urlencoded
后台打印结果:TestEntity -
url-params
后台打印结果:TestEntity
-
同时传值效果
后台打印结果:TestEntity{name='tom,xiaoming', age=18}
后台打印结果:TestEntity -
注意
在Controller中直接定义实体类,会将值赋值到对象中,并且form-data、x-www-form-urlencoded、url-params方式都能正常传值,但是当同时传值时会出现问题。
@RequestParam不能直接作用在实体类上,不然调用接口会抛出异常:
org.springframework.web.bind.MissingServletRequestParameterException: Required request parameter 'testEntity' for method parameter type TestEntity is not present
用类型接收
- controller
此时form-data、x-www-form-urlencoded、url-params方式都能正常传值@PostMapping("/testSend") public void testSend(String name, Integer age) { System.out.println(name); System.out.println(age); }
等同于@PostMapping("/testSend") public void testSend(@RequestParam(required = false) String name, @RequestParam(required = false) Integer age) { System.out.println(name); System.out.println(age); }
用Map接收
- controller
此时后台无法正常接收@PostMapping("/testSend") public void testSend(Map<String, Object> map) { System.out.println(map); }
正确写法是:
此时form-data、x-www-form-urlencoded、url-params方式都能正常传值@PostMapping("/testSend") public void testSend(Map<String, Object> map) { System.out.println(map); }
分类:
Spring MVC
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
· 零经验选手,Compose 一天开发一款小游戏!