不兼容类型的Spring验证

时间:2018-04-16 12:40:58

标签: java spring validation

我有一个包含2个字段的简单表单:

  @Component
public class AddToCartForm {
    @NotNull
    private Long phoneId;

    @Min(value = 1L, message = "Quantity should be integer positive number")
    @NotNull
    private Long quantity;

    public void setPhoneId(Long phoneId) {
        this.phoneId = phoneId;
    }

    public void setQuantity(Long quantity) {
        this.quantity = quantity;
    }

    public Long getPhoneId() {
        return phoneId;
    }

    public Long getQuantity() {
        return quantity;
    }
}

控制器:

@RequestMapping(method = RequestMethod.POST)
    public @ResponseBody
    ModelAndView addPhone(@Validated AddToCartForm form, BindingResult result) throws InvalidAddToCartFormException {
        ModelAndView mv = new ModelAndView(new MappingJackson2JsonView());
        if(result.hasErrors()){
            throw new InvalidAddToCartFormException(result.getFieldError().getDefaultMessage());
        }
        else {
            cartService.addPhone(form.getPhoneId(), form.getQuantity());
            mv.addObject("itemsAmount", cartService.getCart().getItemsAmount());
            mv.addObject("subtotal", cartService.getCart().getSubtotal());
            mv.setStatus(HttpStatus.OK);
        }
        return mv;
    }
@ExceptionHandler(InvalidAddToCartFormException.class)
    public @ResponseBody @ResponseStatus(HttpStatus.BAD_REQUEST) String handleInvalidAddToCartException(InvalidAddToCartFormException e){
        return e.getMessage();
    }

问题是当我尝试输入类似" qwe"我在消息中得到NumberFormatException而不是"值应该是正数",有没有办法以良好的方式处理这些输入?

1 个答案:

答案 0 :(得分:0)

将@Validated注释更改为@Valid(来自javax.validation)。

此外,您不需要实现自己的异常。如果表单无效,Spring会在到达您的代码之前自动抛出异常。