springboot 服务端表单验证

1.pom.xml

springboot-2.3.0的 spring-boot-starter-web启动器好像不包含 spring-boot-starter-validation启动器,需要自己添加

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>    

2.对controller接受的参数进行表单验证分成两种情况,一种是对实体对象进行校验,一种是非实体对象进行校验。

 2.1对实体对象进行校验:

pojo类:

public class Users {
    /*@NotNull(message = "userId不能为空")*/
    @NotNull(message = "{userId.notnull}")
    private Integer userId;
    /*@NotBlank(message = "userName不能为空")*/
    @NotBlank(message = "{userName.notnull}")
    private String userName;
    /*@NotBlank(message = "userSex不能为空")*/
    @NotBlank(message = "{userSex.notnull}")
    private String userSex;
    /*@NotBlank(message = "password不能为空")*/
    @NotBlank(message = "{password.notnull}")
    private String password;

    public Users(@NotNull Integer userId, @NotBlank String userName, @NotEmpty String userSex, @NotNull String password) {
        this.userId = userId;
        this.userName = userName;
        this.userSex = userSex;
        this.password = password;
    }

    public Users() {
    }

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserSex() {
        return userSex;
    }

    public void setUserSex(String userSex) {
        this.userSex = userSex;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "Users{" +
                "userId=" + userId +
                ", userName='" + userName + '\'' +
                ", userSex='" + userSex + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}
  • @Notnull:对字符串来说不可以为null,但可以为空,对基本数据类型的封装类来说,不可以为null(基本数据类型的封装类没有空),对集合来说可以为空,但size可以为0
  • @NotBlank:只能作用于String字符串,因为会调用trim()方法,trim():去除字符串的头尾空格
  • @NotEmpty:主要用于集合(也可用在string,但不会去除空格,不可用于基本数据类型的封装类),集合不能为空,且长度大于0 
  • @Length:判断字符长度,闭区间 
  • @Max:判断数值最大值 
  • @Min:判断数值最小值 
  • @Email:判断邮箱是否合法
  • 以上注解可以组合使用 

 错误信息可以自定义,通过注解的message属性自定义,有两种方式:

  • message = "{写错误信息}" 
  • 在resources下新建ValidationMessages.properties,需要注意的是需要利用jdk/bin目录下native2ascii.exe的工具进行编码转换。
#用户ID不能为空
userId.notnull=\u7528\u6237ID\u4e0d\u80fd\u4e3a\u7a7a 
#用户姓名不能为空
userName.notnull=\u7528\u6237\u59d3\u540d\u4e0d\u80fd\u4e3a\u7a7a
#用户性别不能为空
userSex.notnull=\u7528\u6237\u6027\u522b\u4e0d\u80fd\u4e3a\u7a7a
#用户密码不能为空
password.notnull=\u7528\u6237\u5bc6\u7801\u4e0d\u80fd\u4e3a\u7a7a

 controller类:

  /*
    *
    * @Validated 对该对象进行数据校验
    *
    * BindingResult:users对象校验不合法的信息
    *
    * 如果有多个对象需要进行校验,那么每个对象后面都需要加bindingResult对象
    *
    * SpringMvc会将users放到model对象中,防止前端报错。model中key的名称会使用对象的类型并且用驼峰规则来命名,可以通过@ModelAttribute自定义key
    *
    * */
    @RequestMapping("/addUser")
    public String addUser(@ModelAttribute("u") @Validated Users users, BindingResult bindingResult) {
        //hasErrors()是否含有关于数据校验的错误信息
        if(bindingResult.hasErrors()){
            return "addUser";
        }
        return "OK";
    }

 addUser.html:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <link rel="shortcut icon" href="../resources/favicon.ico" th:href="@{/static/favicon.ico}">
    <title>springbootjdbc</title>
</head>
<body>
    <form th:action="@{/user/addUser}" method="post">
        @NotBlank-string:<input type="text" name="userName"><font color="red"><span th:errors="${u.userName}"></span></font><br>
        @NotNull-Integer:<input type="text" name="userId"><font color="red"><span th:errors="${u.userId}"></span></font><br>
        @NotEmpty-string:<input type="text" name="userSex"><font color="red"><span th:errors="${u.userSex}"></span></font><br>
        @NotNull-string:<input type="text" name="password"><font color="red"><span th:errors="${u.password}"></span></font><br>
        <input type="submit" value="OK">
    </form>
</body>
</html>

 

2.2对非实体对象进行校验:

controller类:

 
  /*
    * BindingResult类型是针对于实体类的,这里无法使用,想要返回错误信息,需要配置全局异常信息页面
    * */
    @RequestMapping("/findUser")
    public String findUser(@NotBlank(message = "用户名不能为空") String userName) {
        System.out.println(userName);
        return "OK";
    }

 GlobalException类(全局异常类配置):

@Configuration
public class GlobalException implements HandlerExceptionResolver {

    /*
     * httpServletRequest产生异常的请求对象
     * httpServletResponse产生异常的响应对象
     * handler此次产生异常的handler对象
     * e 产生异常的异常对象
     * */
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, Exception e) {
        ModelAndView mv = new ModelAndView();
        //判断不同异常类型,做不同视图跳转
        if(e instanceof ConstraintViolationException){
            mv.setViewName("findUser");
        }
        mv.addObject("error", e.getMessage().split(":")[1]);
        return mv;
    }
}

 findUser.html:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <link rel="shortcut icon" href="../resources/favicon.ico" th:href="@{/static/favicon.ico}">
    <title>springbootjdbc</title>
</head>
<body>
    <form th:action="@{/user/findUser}" method="post">
        userName:<input type="text" name="userName"><font color="red"><span th:text="${error}"></span></font><br>
        <input type="submit" value="OK">
    </form>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/activestruggle/p/12901535.html