Spring Boot 参数校验

参考链接: lhttps://www.cnblogs.com/cjsblog/p/8946768.html.
参考https://www.jianshu.com/p/1dff31a1649d
BindingResult 自定义错误信息:
链接: https://blog.csdn.net/zhengun/article/details/84918567.

一:@Valid用法:

准备工作,springboot导入依赖pom:

<!--validation-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-validation</artifactId>
			<version>2.2.10.RELEASE</version>
</dependency>

第一步;先在实体类中使用注解(javax.validation.constraints下的,需要先pom中使用)。如下:

package com.fan.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.List;

//使用Lombok
@Entity
@Table(name = "t_tag")
@AllArgsConstructor
@NoArgsConstructor
@Data
public class Tag {
    @Id
    @GeneratedValue
    private Long id;

    //(1)后台校验第一步,在属性上使用avax.validation.constraints
    @NotBlank(message = "标签不能为空")
    private String name;

    @ManyToMany(mappedBy = "tags")//被维护的关系
    private List<Blog> blogs = new ArrayList<>();

}

第二步:controller中逻辑的编写

//新增 提交
    @PostMapping("/tags")
    public String postInput(@Valid Tag tag,BindingResult bindingResult,
                            RedirectAttributes redirectAttributes){

        //2.入参不能为空的逻辑,这里配合@NotBlank(message = "标签不能为空")使用
        if(bindingResult.hasErrors()){
            /*bindingResult.getFieldError.getDefaultMessage()
            用于获取相应字段上添加的message中的内容,
            如:@Min注解中message属性的内容(注: 通常不在这里处理异常, 由统一的exceptioin全局异常处理)
             */
             
            //System.out.println(bindingResult.getFieldError().getDefaultMessage());
           
            return "admin/tags-input";
        }

        Tag tag1 = tagService.saveTag(tag);
        //1.当新增成功时和不成功时,提示
        if(tag1 == null){
            redirectAttributes.addFlashAttribute("message","添加失败");
        }else{
            redirectAttributes.addFlashAttribute("message","添加成功");
        }
        return "redirect:/admin/tags";
    }

其中@Valid Tag tag,BindingResult bindingResult要连接着一起用,@Valid 注解,表示我们对这个对象属性需要进行验证,@Valid用在要校验的实体前,BindingResult 是放验证的结果的。 RedirectAttributes redirectAttributes是带消息的重定向。
注意后台获取信息这样做
bindingResult.getFieldError.getDefaultMessage()
用于获取相应字段上添加的message中的内容,
如: @NotBlank(message = “标签不能为空”)注解中message属性的内容(注: 通常不在这里处理异常, 由统一的exceptioin全局异常处理)

如果想要将这些错误信息显示到前端页面,这样做:
第1步:将这段代码放到html中:

 <!--/*/
                <div class="ui negative message" th:if="${#fields.hasErrors('name')}">
                    <i class="close icon"></i>
                    <div class="header">验证失败</div>
                    <p th:errors="*{name}">提交信息不符合规则</p>
                </div>
 /*/-->

完整的代码:

<form  th:action="@{/admin/tags}" method="post" th:object="${tag}" class="ui form">

               <div class=" field"><!--required前端校验,必须的-->
                   <div class="ui left label fluid input">
                       <label class="ui teal basic label" >名称</label>
                       <!--th:value="*{name}":将填写的输入框的value赋值到type.name中,为了防止null,拿到内部的name-->
                       <input type="text"  placeholder="标签名称" th:field="*{name}" >
                   </div>
               </div>
               <br>
               <br>
               <br>
               <br>

               <!--前端form表单验证,错误提示,对应下面的js:$('.ui.form').form({-->
               <div class="ui error message"></div>

               <!--**************************后端校验提示***${#fields.hasErrors('name')}需要通过th:object给name赋值*****************************************-->
               <!--/*/
               <div class="ui negative message" th:if="${#fields.hasErrors('name')}">
                   <i class="close icon"></i>
                   <div class="header">验证失败</div>
                   <p th:errors="*{name}">提交信息不符合规则</p>
               </div>
               /*/-->

               <div class="ui right aligned container">
                   <button type="button" class="ui button" onclick="window.history.go(-1)">返回</button>
                   <button  class="ui teal submit button">提交</button>
               </div>
           </form>

下面展示一个小的案例:

其实只要在form表单中的input标签下,写

< p th:if="${#fields.hasErrors(‘变量名’)}" th:errors="*{变量名}"></ p>
例子:

    <p th:if="${#fields.hasErrors('age')}" th:errors="*{age}"></p>

完整的代码:

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<!-- 引入属性xmlns:th="http://www.thymeleaf.org" 来启用thymeleaf模板
thymeleaf 相当于jsp -->
<head>
<title>添加用户</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <form  th:action="@{/adduser}" th:object="${user}" method="post">
        <label for="name">姓名</label>
        <input type="text" th:field="*{name}" id="name" placeholder="Name">

        <p th:if="${#fields.hasErrors('name')}" th:errors="*{name}"></p>


        <label for="age">年龄</label>
        <input type="text" th:field="*{age}" id="age" placeholder="age">

        <p th:if="${#fields.hasErrors('age')}" th:errors="*{age}"></p>


        <label for="email">邮箱</label>
        <input type="text" th:field="*{email}" id="email" placeholder="Email">
        <p th:if="${#fields.hasErrors('email')}" th:errors="*{email}"></p>


        <input type="submit" value="保存">
    </form>
</body>
</html>
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值