问题描述
代码给出错误
它向ajax调用发送JSON响应.我使用休眠来持久化对象.
It sends a JSON response to an ajax call. I use hibernate to persist the objects.
@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对象.
But when I create a new object and copy the parameters to the other object, it works fine. The second method(Not a good method of course) works well. All the parameters in the request object are set to the cse object as well.
@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;
}
第一种方法有什么问题?
What is wrong in the first method?
推荐答案
在第一种情况下,Jackson无法反序列化您的响应.我建议将您的返回类型更改为Map<String, ? extends object>
让我们知道问题是否仍然存在
In the first case Jackson is not able to deserialize your response. I would suggest changing your return type to Map<String, ? extends object>
Let us know if the problem persists
这篇关于spring mvc控制器错误java.lang.IllegalStateException:参数[0]没有合适的解析器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!