Java | @Validated注解校验

导入依赖

<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.1.2.Final</version>
</dependency>

前端

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>注册</title>
</head>
<body>
<form:form action="register" commandName="user">
    <p>
        <label for="name">用户名:</label>
        <input type="text" name="name" id="name">
        <form:errors path="name"></form:errors>
    </p>
    <p>
        <label for="password">密码:</label>
        <input type="password" name="password" id="password">
        <form:errors path="password"></form:errors>
    </p>
    <p>
        <label for="password2">确认密码:</label>
        <input type="password" name="password2" id="password2">
    </p>
    <p>
        <label for="email">邮箱:</label>
        <input type="text" name="email" id="email">
        <form:errors path="email"></form:errors>
    </p>
    <p>
        <label for="age">年龄:</label>
        <input type="text" name="age" id="age">
        <form:errors path="age"></form:errors>
    </p>
    <p>
        <label for="gender">性别:</label>
        <input type="text" name="gender" id="gender">
        <form:errors path="gender"></form:errors>
    </p>
    <span>${msg}</span>
    <p>
        <button formmethod="get">注册</button>
        <button type="reset">重置</button>
        <a href='${pageContext.request.contextPath}/indexLogin'>返回登录</a>
    </p>
</form:form>
</body>
</html>

entity

package com.java.entity;

import com.java.group.UserLoginGroup;
import com.java.group.UserRegGroup;
import lombok.Data;
import org.hibernate.validator.constraints.Range;

import javax.validation.constraints.*;

@Data
public class User {
    private int id;

    @NotEmpty(groups = {UserLoginGroup.class, UserRegGroup.class}, message = "用户名不能为空")
    @NotNull(groups = {UserLoginGroup.class, UserRegGroup.class}, message = "用户名不能为空")
    @Pattern(groups = {UserLoginGroup.class, UserRegGroup.class}, regexp = "[a-zA-Z0-9\u4e00-\u9fa5]{2,20}", message = "用户民必须为2-20个字母加数字")
    private String name;

    @NotEmpty(groups = {UserLoginGroup.class, UserRegGroup.class}, message = "密码不能为空")
    @NotNull(groups = {UserLoginGroup.class, UserRegGroup.class}, message = "密码不能为空")
    @Size(groups = {UserLoginGroup.class, UserRegGroup.class}, min = 3, max = 16)
    private String password;

    @NotEmpty(groups = {UserRegGroup.class}, message = "邮箱能为空")
    @NotNull(groups = {UserRegGroup.class}, message = "邮箱能为空")
    @Email(groups = {UserRegGroup.class}, regexp = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$", message = "邮箱格式不正确")
    private String email;

    @NotNull(groups = {UserRegGroup.class}, message = "年龄不能为空")
    @Range(groups = {UserRegGroup.class}, min = 0, max = 100, message = "年龄必须在0-100之间")
    private int age;

    @NotNull(groups = {UserRegGroup.class}, message = "性别不能为空")
    private char gender;

    private Integer point = 0;
    private Integer state;
}

controller

/**
     * 注册
     *
     * @param user
     * @param errors
     * @param password2
     * @return
     */
    @RequestMapping(value = "/register", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ModelAndView register(@Validated({UserLoginGroup.class, UserRegGroup.class}) User user, Errors errors, @RequestParam(defaultValue = "") String password2) {
        ModelAndView modelAndView = new ModelAndView();
        // 如果存在异常注册失败
        if (errors.hasErrors()) {
            // 如果有异常跳转到注册界面
            modelAndView.setViewName("forward:/indexRegister");
            return modelAndView;
        }
        // 判断两次密码是否一致
        if (!password2.equals(user.getPassword())) {
            errors.rejectValue("password", "", "两次密码输入不一致");
            modelAndView.setViewName("forward:/indexRegister");
            return modelAndView;
        }
        // 判断用户名是否重复
        int i = userService.selectUserByName(user.getName());
        if (i > 0) {
            errors.rejectValue("name", "", "用户名已注册");
            modelAndView.setViewName("forward:/indexRegister");
            return modelAndView;
        } else {
            // 添加用户
            int result = userService.addUser(user);
            if (result >= 1) {
                // 注册成功,跳转到登录界面
                modelAndView.setViewName("redirect:/indexLogin");
                return modelAndView;
            } else {
                // 注册失败
                modelAndView.setViewName("forward:/indexRegister");
                modelAndView.addObject("msg", "注册失败!");
                return modelAndView;
            }
        }
    }

groups
在这里插入图片描述
为项目配置全局统一异常拦截器

package com.java.advice;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@ControllerAdvice
@ResponseBody
public class MyExceptionHandler {

    /**
     * 原理AOP,捕获全局异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    private ModelAndView exHandler(Exception ex) {
        ModelAndView mav = new ModelAndView("error.jsp");
        mav.addObject("msg", ex.getMessage());
        return mav;
    }
}
发布了28 篇原创文章 · 获赞 13 · 访问量 7824

猜你喜欢

转载自blog.csdn.net/y1534414425/article/details/104737397
今日推荐