关于springboot 接口中 参数为两个实体类的解决办法

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

1.分装成dto

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

1
2
3
4
{
    teacher: value1,
    course: value2
}

这样就可以了

2.采用@InitBinder注解

1
2
3
4
5
6
7
8
9
@InitBinder("student")
    public void initBinderStudent(WebDataBinder binder){
      binder.setFieldDefaultPrefix("student.");
    }
 
@InitBinder("course")
    public void initBinderCourse(WebDataBinder binder){
      binder.setFieldDefaultPrefix("course.");
    }

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

@InitBinder() 中间的value值,用于指定表单属性或请求参数的名字,符合该名字的将使用此处的DataBinder
注意: binder.setFieldDefaultPrefix("student."),这里的"."千万别忘记了!!!
1
2
3
4
5
6
7
8
9
10
public class Student implements Serializable{  
  String id;  
  String note;  
  //get..set....  
}  
public class Course implements Serializable{  
  String id;  
  String note;
  //set..get...  
}

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@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;  
    }

@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

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

关注我们