spring 通过@responsebody接收多个对象参数

springmvc不支持多个@RequestBody.

requestbody的含义是在当前对象获取整个http请求的body里面的所有数据,因此spring就不可能将这个数据强制包装成Course或者List类型,并且从@requestbody设计上来说,只获取一次就可以拿到请求body里面的所有数据,就没必要出现有多个@requestbody出现在controller的函数的形参列表当中。

解决方法:

1、组装一个新的实体,将需要的entity都装进去,但是不够优雅。

2、用Map<String,Object>接收参数,自己反序列化得到对应的entity。

前台js

       var examRecord={userId:"ceshi"};
       var answersList=[];  
       answer1={answer:"232"};
       answer2={answer:"122"};
       answersList.push(answer1);
       answersList.push(answer2);
       console.log(examRecord)
        $.ajax({
           type: "POST",
           cache: false,
          // headers: {"cache-control": "no-cache"},
           dataType: "json",
           contentType: "application/json",
           url: path+"/examController/addExamRecord",
           /* data: JSON.stringify({answersList:JSON.stringify(checkQues),examRecord:JSON.stringify(examRecord)}), */
           data:JSON.stringify({examRecord:examRecord,answersList:answersList}),
           async: false,
           success: function (data) {
           }
       }); 

后台代码:

    @RequestMapping("/addRandomExam")
    @ResponseBody
    public ResJson addRandomExam(@RequestBody Map<String,Object>param) {

        Object examPaper=param.get("examPaper");
        Object examPaperRandomRules=param.get("examPaperRandomRuleList");
        ExamPaper paper=JSONHelper.toBean(examPaper,ExamPaper.class); 
        List<ExamPaperRandomRule> examPaperRandomRuleList=JSONHelper.toList(examPaperRandomRules,ExamPaperRandomRule.class); 
    }

json 工具类:

public final class JSONHelper {

       /***
     * 将将对象转换为传入类型的对象
     * 
     * @param <T>
     * @param object
     * @param beanClass
     * @return
     */
    public static <T> T toBean(Object object, Class<T> beanClass) {
        JSONObject jsonObject = JSONObject.fromObject(object);

        return (T) JSONObject.toBean(jsonObject, beanClass);
    }
    /***
     * 将对象转换为传入类型的List
     * 
     * @param <T>
     * @param jsonArray
     * @param objectClass
     * @return
     */
    public static <T> List<T> toList(Object object, Class<T> objectClass) {
        JSONArray jsonArray = JSONArray.fromObject(object);

        return JSONArray.toList(jsonArray, objectClass);
    }

}

3、实现自己的HandlerMethodArgumentResolver

猜你喜欢

转载自www.cnblogs.com/magic101/p/10524703.html
今日推荐