【问题标题】:Error in Post method spring mvcPost方法spring mvc中的错误
【发布时间】:2017-11-07 00:36:26
【问题描述】:

我需要捕获验证错误以发送到 View。 我以这种方式遵循了几个教程: 我的 Bean 验证方法:

   @RequestMapping(value = "/novo", method = RequestMethod.POST)
    public ModelAndView salvar(@Valid Cliente cliente, BindingResult result
        , RedirectAttributes attributes) {
    if (result.hasErrors()) {
        return novo(cliente);
    }

    ModelAndView mv = new ModelAndView("redirect:/clientes/novo");
    attributes.addFlashAttribute("mensagem", "Cliente salvo com sucesso.");
    return mv;
}

我的班级客户:

 public class Cliente implements EntityModal<Long> {

private Long id;

@NotBlank(message = "Nome é obrigatório")
private String nome;

@CPF(message = "CPF inválido")
private String cpf;

@NotNull(message = "Informe o sexo")
private Sexo sexo;

@NotNull(message = "Idade é obrigatória")
@Min(value = 18, message = "Idade deve ser maior ou igual que 18")
private Integer idade;

@Size(max = 50, message = "A observação não pode ter mais que 50 caracteres")
private String observacao;
 //get and setters...
}

错误:

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 org.springframework.web.servlet.ModelAndView

【问题讨论】:

    标签: java spring spring-mvc bean-validation


    【解决方案1】:

    在您的模型对象中添加@ModelAttribute

    @RequestMapping(value = "/novo", method = RequestMethod.POST)
    public ModelAndView salvar(@Valid @ModelAttribute("cliente") Cliente cliente, BindingResult result
            , RedirectAttributes attributes) {
    
    }
    

    【讨论】:

    • 因为要放Attribute模型?我看的教程没有这个
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-01
    • 2019-02-02
    • 2014-04-25
    • 1970-01-01
    • 2018-01-24
    相关资源
    最近更新 更多