我的要求是使用 Spring 3.0 和 Hibernate Validator 对表单执行服务器端验证。请记住,我正在使用 AJAX 调用提交表单。我的 Controller 类代码如下所示。
public ModelAndView generatePdfReport(@ModelAttribute("reports") @Valid ReportsCommand model, BindingResult result, ModelAndView modelAndView,
HttpServletRequest request, HttpServletResponse response) throws Exception {
if (result.hasErrors()) {
throw new BindException(result);
}
else{
...
}
更新...
@ExceptionHandler(BindException.class)
public @ResponseBody String handleException(BindException e,HttpServletRequest request, HttpServletResponse response)
{
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return e.getMessage();
}
这是我放置在 Controller 中的处理程序方法。我使用了 @ResponseBody 注释,但它仍然以 html 格式而不是 JSON 格式显示响应... 我的代码有什么问题.. 下面是我正在验证的字段
@Size(min = 2, max = 3, message = "calltype must between 2 to 3 Characters.")
private String callType;
如果我给的大小超过三,它就会进入 if 并抛出异常。我想要的是,我想处理这个异常并返回 json 响应。也许我可以使用 @ExceptionHandler 来做到这一点但不知道如何。或者解决此问题的任何其他解决方案也将不胜感激。
最佳答案
导入此包
import org.springframework.validation.BindException
不是这个
import java.net.BindException
关于spring - 如何使用@ExceptionHandler处理绑定(bind)异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11014055/