[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); }

浙公网安备 33010602011771号