【springboot thymeleaf】实体上的非空校验@NotBlank(message = "提示信息") 在前端页面展示的方式

【springboot thymeleaf】实体上的非空校验@NotBlank(message = “提示信息”) 在前端页面展示的方式

举例


实体类

@Setter
@Getter
@ToString
@NoArgsConstructor
@Entity
@Table(name = "t_type")
public class Type {
    @Id
    @GeneratedValue
    private Long id;
    /*通过注解的方式,添加校验
    * name不能为空
    * 使用注解@NotBlank(message = "分类名称不能为空")
    * 如果为空,后台将会抛出异常
    * */
    @NotBlank(message = "分类名称不能为空")
    private String name;//分类名称
}

html页面

<form action="admin/types" th:action="@{/admin/types}" th:object="${type}" method="post">
    <input type="hidden" name="id">
    <div>
	    <div>
	         <label>名称label>
	         <input type="text" name="name" th:value="*{name}" placeholder="名称">
	    div>
    div>
    <div> 
                    
    div>
   <div>
       <button type="button" onclick="window.history.go(-1)" >返回button>
       <button type="submit">提交button>
   div>
form>

Controller类


/*跳转到type新增页面
* 添加后端验证时,需要创建一个Type对象
* */
@GetMapping("/types/to_add_type_page")
public String toAddTypePage(Model model){
    model.addAttribute("type",new Type());
    return "admin/types-input";
}

@Controller
@RequestMapping("/admin")
public class TypeController {

    @Autowired
    private TypeService typeService;
    
    /*
    * 在形参上添加注解@Valid
    * 同时,添加BindingResult result来接受后台message的消息
    * */
    @PostMapping("/types")
    public String saveType(@Valid Type type, BindingResult result, RedirectAttributes attributes){
        /*如果result有错误,则返回新增页面(types-input.html)*/
        if (result.hasErrors()){
            return "admin/types-input";
        }
        Type type1 = typeService.saveType(type);
        //没错误返回列表页面
        return "redirect:/admin/types";
    }
}

你可能感兴趣的:(springboot,spring,boot,html,java)