首页 > 解决方案 > 如何验证电子邮件spring boot thymeleaf

问题描述

当用户想在我的网站上注册时,我想验证电子邮件。我设置@NotBlank@Email注释,@Valid在 post 方法上做了注释,但我不知道如何让它正常工作。在 /register 端点应用程序显示 error500。如何更改我的代码以使其正常工作?用户名不应该用空白或不正确的电子邮件注册,但我无法解决。

应用用户类:

@Data
@Entity
public class AppUser implements UserDetails {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(unique = true)
    @NotBlank(message = "login is required")
    private String username;
    @NotBlank(message = "password is required")
    private String password;
    private String role;
    @Column(unique = true)
    @Email(message = "Wrong e-mail")
    private String email;
    private String phone;

    public AppUser() {
    }

用户控制器类:

@Controller
public class UserController {


    @GetMapping("register")
    public String register(Model model) {
        model.addAttribute("user", new AppUser());
        return "register";
    }

    @PostMapping("/registerOk")
    public String registerOk(@Valid AppUser appUser, Errors errors) {
        if (errors.hasErrors()) {
            return "register";
        }
        userService.addUser(appUser);
        return "redirect:register?success";
    }
}

我的 register.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
    <meta charset="UTF-8">
    <title>Rejestracja</title>
    <link rel="stylesheet" type="text/css" th:href="@{/css/index.css}"/>
</head>
<body>

<form class="box" th:action="@{/registerOk}" method="post">
    <div th:if="${param.success}">
        <div class="alert alert-info"><span style="color: white">Register is sucessful, check your e-mail adress.</span></div>
    </div>
    <h1>Register new account: </h1>
    <input type="text" name="username" placeholder="login">
<span class="validationError"
            th:if="${#fields.hasErrors('username')}"
            th:errors="*{username}">Username Error</span>
    <input type="password" name="password" placeholder="password" id="hide">
    <input type="text" name="email" placeholder="E-Mail">
    <input type="text" name="phone" placeholder="phone number">
    <input type="submit" value="Register me!">
    <div class="form-group">
        <span style="color: white">Already registered? <a href="/" th:href="@{/login}">Login</a></span>
    </div>
</form>

</body>
</html>

标签: spring-bootthymeleaf

解决方案


使用type="email"而不是text.

<input type="email" name="email" placeholder="E-Mail">

如果required您希望输入字段作为强制输入,请使用。

<input type="email" name="email" placeholder="E-Mail" required>

推荐阅读