关于springboot post方法参数为两个实体类的解决办法


title: 关于springboot post方法参数为两个实体类的解决办法
cover: /img/1.jpg

前端调用后端api某个post方法的时候,如果发现方法的参数为两个实体类的时候,我们像往常一样传参,后台会发生接收不到参数的问题。

1.分装成dto

如果两个参数都是实体类的话,可以采用将两个实体类封装成一个实体类的方法。比如说有两个实体类,Techer和Course 这是两个pojo 那么我们可以定义一个实体类叫做 TeacherCourseDto 他的属性只有两个,一个是Teacher teacher一个是Course course 这样前台传参的时候

{
    teacher: value1,
    course: value2
}

这样就可以了

2.采用@InitBinder注解

@InitBinder("student")
    public void initBinderStudent(WebDataBinder binder){
      binder.setFieldDefaultPrefix("student.");
    }

@InitBinder("course")
    public void initBinderCourse(WebDataBinder binder){
      binder.setFieldDefaultPrefix("course.");
    }

@InitBinder() 中间的value值,用于指定表单属性或请求参数的名字,符合该名字的将使用此处的DataBinder
注意: binder.setFieldDefaultPrefix(“student.”),这里的"."千万别忘记了!!!

public class Student implements Serializable{  
  String id;  
  String note;  
  //get..set....  
}  
public class Course implements Serializable{  
  String id;  
  String note;
  //set..get...  
}

这边两个实体类,加上我们上面的initBinder注解 还要在ctrl上做点动作

@Controller  
@RequestMapping("/classtest")  
public class TestController {  
    // 绑定变量名字和属性,参数封装进类  
    @InitBinder("student")  
    public void initBinderUser(WebDataBinder binder) {  
        binder.setFieldDefaultPrefix("student.");  
    }  
    // 绑定变量名字和属性,参数封装进类  
    @InitBinder("course")  
    public void initBinderAddr(WebDataBinder binder) {  
        binder.setFieldDefaultPrefix("course.");  
    }  
      
      
    @RequestMapping("/methodtest")  
    @ResponseBody  
   public Map<String,Object> test(@ModelAttribute("student") Student student,@ModelAttribute("course") Course course){  
        Map<String,Object> map=new HashMap<String,Object>();  
        map.put("student", student);  
        map.put("course", course);  
        return map;  
    }

ctrl上的参数使用@ModelAttribute注解指定,这样就可以实现参数两个实体类,不用再去多写一个dto了
当然这种方法也有缺陷,具体参考SpringMVC表单多对象传递小技巧——@InitBinder

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值