一 controller 参数校验
参考: https://juejin.cn/post/6844903902811275278
1. 当参数中有 org.springframework.validation.Errors 的子类, 例如 BindingResult, 异常不会被抛出。 源码见: org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor#resolveArgument
代码示例如下:
import com.alibaba.fastjson.JSON; import com.ql.common.domain.Result; import com.ql.service.validation.Item; import org.springframework.context.support.DefaultMessageSourceResolvable; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.stream.Collectors; /** * 参数校验 * 参考文档: https://blog.csdn.net/qq_27680317/article/details/79970590 */ @RequestMapping(value = "/item") @RestController public class ItemController { /** * 有BindingResult参数 不抛出异常 * * @param item * @param result * @return */ @RequestMapping("add") public Result<Void> addItem(@Validated @RequestBody Item item, BindingResult result) { System.out.println("item =: " + JSON.toJSONString(item)); List<FieldError> fieldErrors = result.getFieldErrors(); List<String> collect = fieldErrors.stream() .map(DefaultMessageSourceResolvable::getDefaultMessage) .collect(Collectors.toList()); return Result.successResult(null, "addItem over collect = :" + JSON.toJSONString(collect)); } /** * 正常参数异常校验, 抛出异常, 统一异常处理 * * @param item * @return */ @RequestMapping("add2") public Result<Void> addItem2(@Validated @RequestBody Item item) { return Result.successResult(null, "addItem2 over"); } }
标签:java,校验,springframework,item,参数,Result,import,org,annotation From: https://www.cnblogs.com/daixianjun/p/param-validation.html