SpringBoot2.x系列教程(二十二)简单参数校验及统一异常处理

在之前章节,我们将了如何使用校验框架对JavaBean中的参数进行校验,那么如果只是一些简单参数该如何校验呢?是否也可以用BindingResult接收呢?

很遗憾,针对简单参数(比如String,Integer等)并无法使用BindingResult接收。如果强行使用,要么无效(特定场景)要么则会抛出如下异常:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalStateException: An Errors/BindingResult argument is expected to be declared immediately after the model attribute, the @RequestBody or the @RequestPart arguments to which they apply: public java.lang.String com.secbro2.controller.AccountController.getAmountByAccountNo(java.lang.String,org.springframework.validation.BindingResult)

也就是说针对简单参数,如果我们使用校验注解进行校验,则会抛出异常,通过页面访问时会返回500错误。

面对这种情况有两种处理策略:如果是调整页面的时候参数校验失败的话,让其跳转错误页面(后面章节再详细讲)。如果是接口参数校验失败的话,可以进行统一处理,并返回。

首先不说使用BindingResult接收参数,当我们使用如下方式,对简单参数进行校验时,统一会抛出异常。具体使用如下:

@Validated
@RestController
public class AccountController {

	@GetMapping("/getAmountByAccountNo")
	public String getAmountByAccoun

猜你喜欢

转载自blog.csdn.net/wo541075754/article/details/103903995
今日推荐