话不多说先放代码,实体类代码如下
package com.ccnu.po; import javax.persistence.*; import javax.validation.constraints.NotBlank; import java.util.ArrayList; import java.util.List; @Entity @Table(name = "t_type") public class Type { @Id @GeneratedValue private Long id; @NotBlank(message = "分类名称不能为空") private String name; @OneToMany(mappedBy = "type") private List<Blog> blogs = new ArrayList<>(); public Type() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Blog> getBlogs() { return blogs; } public void setBlogs(List<Blog> blogs) { this.blogs = blogs; } @Override public String toString() { return "Type{" + "id=" + id + ", name='" + name + '\'' + '}'; } }
此处使用@NotBlank注解对name进行非空验证
接下来先放一段错误的controller层代码
@PostMapping("/type") public String post(@Valid Type type, RedirectAttributes attributes, BindingResult result){ if (result.hasErrors()){ return "admin/type-input"; } Type t = typeService.saveType(type); if(t == null){ attributes.addFlashAttribute("message","操作失败"); }else{ attributes.addFlashAttribute("message","操作成功"); } return "redirect:/admin/type"; }
@Valid注解和BindingResult参数也都写了,但后台仍然包如下错误
Field error in object 'type' on field 'name': rejected value []; codes [NotBlank.type.name,NotBlank.name,NotBlank.java.lang.String,NotBlank]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [type.name,name]; arguments []; default message [name]]; default message [分类名称不能为空]]
最后经查询官方文档知BindingResult参数必须紧跟着@Valid修饰的参数后面(如果写在前面或者中间隔了一个参数都将不起作用),正确地Controller层代码如下
@PostMapping("/type") public String post(@Valid Type type, BindingResult result, RedirectAttributes attributes ){ if (result.hasErrors()){ return "admin/type-input"; } Type t = typeService.saveType(type); if(t == null){ attributes.addFlashAttribute("message","操作失败"); }else{ attributes.addFlashAttribute("message","操作成功"); } return "redirect:/admin/type"; }