Post 方法 spring mvc 中的错误
Error in Post method spring mvc
我需要捕获验证错误以发送到视图。
我以这种方式学习了几个教程:
我的 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;
}
我的 class 客户:
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
在模型对象中添加 @ModelAttribute
。
@RequestMapping(value = "/novo", method = RequestMethod.POST)
public ModelAndView salvar(@Valid @ModelAttribute("cliente") Cliente cliente, BindingResult result
, RedirectAttributes attributes) {
}
我需要捕获验证错误以发送到视图。 我以这种方式学习了几个教程: 我的 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;
}
我的 class 客户:
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
在模型对象中添加 @ModelAttribute
。
@RequestMapping(value = "/novo", method = RequestMethod.POST)
public ModelAndView salvar(@Valid @ModelAttribute("cliente") Cliente cliente, BindingResult result
, RedirectAttributes attributes) {
}