SpringMvc中,校验参数可以使用 @Valid 注解,同时在相应的对象里使用
1 2 3 4 5 6 | @NotBlank ( message = "昵称不能为空" ) @NotNull ( message = "ID不能为空" ) @Pattern ( message = "不能包括空格" , regexp = "\\S+" ) |
等等。
这个校验会把所有的参数都校验一遍,所以它的异常里会好些列表,直接使用e.getMessage(),会输出很多累赘的东西
一个好的解决办法
@Valid 注解校验住的异常是 org.springframework.validation.BindException
所以可以添加一个异常拦截器,专门拦截,并且解析这种异常
具体如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | package cn.jiashubing.config; import cn.jiashubing.result.ResultModel; import org.springframework.validation.BindException; import org.springframework.validation.ObjectError; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import java.util.List; /** * @author jiashubing * @since 2019/6/17 */ @ControllerAdvice public class BingExceptionHandler { @ExceptionHandler (BindException. class ) @ResponseBody public ResultModel handleBindException(Exception e) { //打印校验住的所有的错误信息 StringBuilder sb = new StringBuilder( "参数错误:[" ); List<ObjectError> list = ((BindException) e).getAllErrors(); for (ObjectError item : list) { sb.append(item.getDefaultMessage()).append( ',' ); } sb.deleteCharAt(sb.length() - 1 ); sb.append( ']' ); String msg = sb.toString(); return new ResultModel( false , msg); } } |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自学编程网。
- 本文固定链接: https://zxbcw.cn/post/195822/
- 转载请注明:必须在正文中标注并保留原文链接
- QQ群: PHP高手阵营官方总群(344148542)
- QQ群: Yii2.0开发(304864863)