spring mvc如何处理表单类型转换错误


领域对象包含一个Integer类型的值,在spring的form表单中如果输入错误的字符串,比如“abc”,那么会报错The request sent by the client was syntactically incorrect.这肯定是个类型转换的异常,那么如何捕获这个异常并且重新跳转到表单的编辑页面?

spring-mvc

pludes 8 years, 6 months ago

1.楼主后台在接收参数的时候将Integer参数改为String 然后用正则或是Integer.parseInt捕获异常来判断是否可以转为int型,这样就可以捕获这个异常,然后在request里设置message(错误提示) 重新返回到jsp页面。
2.后台的方法改为无参类型,因为是form提交 后台直接从request里获取name即可获取值
3.最后的设计方法是 界面中 form表单提交前用js做一次验证,后台方法处理时再做一次验证,这种是比较好的

cw123 answered 8 years, 6 months ago


 @ExceptionHandler(MethodArgumentNotValidException.class)
public String (HttpServletRequest request) {
    String referrer = request.getHeader("referer");
    return "redirect:" + referrer ;
}

傲骄不是病 answered 8 years, 6 months ago

根据楼主的报错,我猜测抛出的异常应该是org.springframework.beans.TypeMismatchException,这是SpringMVC报的错误。"The request sent by the client was syntactically incorrect."这应该是apache封装之后显示的错误信息。对于spring抛出的这种异常,使用


 @ExceptionHandler({ TypeMismatchException.class })
@ResponseBody
public String ParameterErrorExceptionHandeler(RuntimeException exception, HttpServletRequest request)
            throws IOException {
       ××××××
       return 。。。            
}

就能接收到那个异常。当然你也可以在web.xml里面配置400异常页面,或者如果你使用了springMVC的Resolve,也可以在viewResolve里面配置400错误页面。

Arikado answered 8 years, 6 months ago

Your Answer