controller函數中參數列表使用多個@RequestBody


首先出現這種情況是因為有下面這種需求


   
   
  
  
          
  1. $.ajax({
  2. type: "POST",
  3. url: "${pageContext.request.contextPath}/courses",
  4. data: JSON.stringify({
  5. course:course,
  6. courseInfoList:courseInfoList
  7.        }),//將對象序列化成JSON字符串
  8. dataType: "json",
  9. contentType : 'application/json;charset=utf-8', //設置請求頭信息
  10. success: function(data){
  11. },
  12. error: function(res){
  13. }
  14. });

也就是在ajax傳輸數據時有多種數據類型在data域中

從而就會有下面這種controller


   
   
  
  
          
  1. @RequestMapping(method = RequestMethod.POST ,consumes = "application/json")
  2. public String createCourse( @RequestBody Course course, @RequestBody List<CourseInfo> courseInfoList)
  3. {
  4. System. out.println(coursePackage.getCourse());
  5. System. out.println(coursePackage.getCourseInfoList());
  6. return "/createCourse";
  7. }

這樣就會出現400錯誤,服務器無法理解這個請求

原因:

@requestbody的含義是在當前對象獲取整個http請求的body里面的所有數據,因此spring就不可能將這個數據強制包裝成Course或者List類型,並且從@requestbody設計上來說,只獲取一次就可以拿到請求body里面的所有數據,就沒必要出現有多個@requestbody出現在controller的函數的形參列表當中

如果想解決這種問題

1.新建一個包裝上面兩種entity的entity類:


   
   
  
  
          
  1. package com.yyc.entity;
  2. import java.util.List;
  3. public class CoursePackage {
  4. public CoursePackage() {
  5. // TODO Auto-generated constructor stub
  6. }
  7. private Course course;
  8. private List<CourseInfo> courseInfoList;
  9. public void setCourse(Course course)
  10. {
  11. this.course = course;
  12. }
  13. public void setCourseInfoList(List<CourseInfo> courseInfoList)
  14. {
  15. this.courseInfoList = courseInfoList;
  16. }
  17. public Course getCourse()
  18. {
  19. return course;
  20. }
  21. public List<CourseInfo> getCourseInfoList()
  22. {
  23. return courseInfoList;
  24. }
  25. }

然后將controller函數改為


   
   
  
  
          
  1. @RequestMapping(method = RequestMethod.POST ,consumes = "application/json")
  2. public String createCourse( @RequestBody CoursePackage coursePackage,Model model)
  3. {
  4. System. out.println(coursePackage.getCourse());
  5. System. out.println(coursePackage.getCourseInfoList());
  6. return "/createCourse";
  7. }

但是這樣又顯得比較不夠簡潔

2..用Map<String, Object>接受request body,自己反序列化到各個entity中。

例:下面這篇博客比較好:https://www.cnblogs.com/mahuan2/p/6008832.html

原文地址:https://blog.csdn.net/qq_34608620/article/details/80635139


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM