[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 测试
    image

    后台打印结果:TestEntity

  • x-www-form-urlencoded
    image
    后台打印结果:TestEntity

  • url-params
    image

    后台打印结果:TestEntity

  • 同时传值效果
    image
    后台打印结果:TestEntity{name='tom,xiaoming', age=18}
    image
    后台打印结果: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
    @PostMapping("/testSend")
    public void testSend(String name, Integer age) {
    	System.out.println(name);
    	System.out.println(age);
    }
    
    此时form-data、x-www-form-urlencoded、url-params方式都能正常传值
    等同于
    @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);
    }
    
    此时后台无法正常接收
    正确写法是:
    @PostMapping("/testSend")
    public void testSend(Map<String, Object> map) {
        System.out.println(map);
    }
    
    此时form-data、x-www-form-urlencoded、url-params方式都能正常传值
posted @ 2022-09-28 21:00  Yorkey  阅读(163)  评论(0)    收藏  举报