2

当我有以下代码时,我的代码给出 500 错误。它向 ajax 调用发送一个 jason 响应。

    @RequestMapping(value = "/savecourse", method = RequestMethod.POST)
public @ResponseBody
Object saveLecturer(@Valid @ModelAttribute(value = "course") Course course,
        BindingResult result) {

    Map<String, Object> response = new HashMap<String, Object>();

    if (result.hasErrors()) {
        List<ObjectError> results = result.getAllErrors();
        for (ObjectError objectError : results) {
            System.out.println(objectError.getDefaultMessage());
        }
        response.put("message", "Could not add the Course to the system.");
    } else {
        try {
            course.setId(courseDao.saveCourse(course));//returns the id
            response.put("course", course);

        } catch (Exception e) {
            System.out.println(e);

        }
    }

    return response;
}

但是当我创建一个新对象并将参数复制到另一个对象时,它工作正常。第二种方法(当然不是一个好方法)效果很好。请求对象中的所有参数也都设置为 cse 对象。

    @RequestMapping(value = "/savecourse", method = RequestMethod.POST)
public @ResponseBody
Object saveLecturer(@Valid @ModelAttribute(value = "course") Course course,
        BindingResult result) {

    Map<String, Object> response = new HashMap<String, Object>();

    if (result.hasErrors()) {
        List<ObjectError> results = result.getAllErrors();
        for (ObjectError objectError : results) {
            System.out.println(objectError.getDefaultMessage());
        }
        response.put("message", "Could not add the Course to the system.");
    } else {
        try {
            course.setId(courseDao.saveCourse(course));//returns the id
            Course cse = new Course();
            cse.setId(course.getId());
            cse.setCourseName(course.getCourseName());
            cse.setFee(course.getFee());
            Lecturer lec = new Lecturer();
            lec.setId(course.getLecturer().getId());
            lec.setFirstName(course.getLecturer().getFirstName());
            lec.setLastName(course.getLecturer().getLastName());
            cse.setLecturer(lec);
            cse.setGrade(course.getGrade());
            response.put("course", cse);

        } catch (Exception e) {
            System.out.println(e);

        }
    }

    return response;
}

你能告诉我第一种方法有什么问题吗?任何帮助是极大的赞赏。

4

0 回答 0