BindingResult 和 bean 名称 'userData' 的普通目标 object 都不能用作请求属性

Neither BindingResult nor plain target object for bean name 'userData' available as request attribute

我正在尝试按照 this 在尝试注册但未输入正确输入或将输入留空时向用户显示一些错误消息。我在控制台中看到标题中的错误,页面显示此错误消息 There was an unexpected error (type=Internal Server Error, status=500).

我有一个 class 用户没有实现 Serializable 并且与 Userdate 完全一样。

UserData.java

public class UserData implements Serializable{
    
    @NotEmpty(message = "First name can not be empty")
    private String firstName;

    @NotEmpty(message = "Last name can not be empty")
    private String lastName;

    @NotEmpty(message = "Email can not be empty")
//    @Email(message = "Please provide a valid email id")
    private String email;
    
    @NotEmpty(message = "username can not be empty")
    private String username;

    @NotEmpty(message = "Password can not be empty")
    private String password;
    
    private Set<Role> roles=new HashSet<>();

UserService.java

public void save(UserData userData) throws EmailAlreadyExistException {
        if(checkIfUserEmailExist(userData.getEmail())) {
            throw new EmailAlreadyExistException("This email already exist. Use different email.");
        }

        User user = new User();
        BeanUtils.copyProperties(userData, user);
        encodePassword(user, userData);
        userData.setRoles(new HashSet<Role> (Arrays.asList(new Role("user"))));
        userRepository.save(user);
        
    }
    
    // ----------------------------------------------------- helper methods for user validation ------------------------------------------- 
    
     private boolean checkIfUserEmailExist(String email) {
            return userRepository.findByEmail(email) !=null ? true : false;
        }
     
     private void encodePassword( User user, UserData userData){
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }

RegisterationController.java

@Controller
public class RegisterationController {
    
    @Autowired
    private UserService userService;
    
    @GetMapping("/register")
    public String getRegisterPage(ModelMap model) {
        User user = new User();
        model.put("user", user);
        return "register";
    }
    
    @PostMapping("/register")
    public String postRegister(final @Valid UserData userData, final BindingResult bindingResult, final Model model) {
        if(bindingResult.hasErrors()) {
            model.addAttribute("register", userData);
            return "register";
        }
        
        try {
            userService.save(userData);
        } catch (EmailAlreadyExistException e) {
            bindingResult.rejectValue("email", 
                                      "userData.email", 
                     "This email is alraedy taken");
            model.addAttribute("register", userData);
//          e.printStackTrace();
            return "register";
        }
        return "redirect:/";
    }

register.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
</head>
<body class="hold-transition register-page">
  <div class="register-box">
    <div class="card">
      <div class="card-body register-card-body">
        <p class="login-box-msg">Register a new account</p>

        <form action="#" th:action="@{/register}" th:object="${userData}" method="post">
          <div class="alert alert-danger" th:if="${#fields.hasErrors('*')}">
          <p th:each="err : ${#fields.errors('*')}" th:text="${err}"></p>
        </div>
        </form>
        <div class="input-group mb-3">
        <input type="text" class="form-control"  th:field="*{firstName}" placeholder="First Name" th:errorclass="is-invalid">
        <div class="input-group-append">
          <div class="input-group-text">
            <span class="fas fa-user"></span>
          </div>
        </div>
      </div>
        <div class="input-group mb-3">
          <input type="text" class="form-control"  th:field="*{lastName}" placeholder="Last Name" th:errorclass="is-invalid">

          <div class="input-group-append">
            <div class="input-group-text">
              <span class="fas fa-user"></span>
            </div>
          </div>
        </div>
       <div class="input-group mb-3">
          <input type="email" class="form-control" th:field="*{email}" placeholder="Email" th:errorclass="is-invalid">

          <div class="input-group-append">
            <div class="input-group-text">
              <span class="fas fa-envelope"></span>
            </div>
          </div>
        </div>
         <div class="input-group mb-3">
          <input type="text" class="form-control" th:field="*{username}" placeholder="username" th:errorclass="is-invalid">

          <div class="input-group-append">
            <div class="input-group-text">
              <span class="fas fa-envelope"></span>
            </div>
          </div>
        </div>
        
        <div class="input-group mb-3">
          <input type="password" class="form-control" th:field="*{password}" placeholder="Password" th:errorclass="is-invalid">

          <div class="input-group-append">
            <div class="input-group-text">
              <span class="fas fa-lock"></span>
            </div>
          </div>
        </div>
        
        
    </div>
    <!-- /.form-box -->
  </div><!-- /.card -->
</div>

</body>

</html>

打开注册页面时,您正在发送 user 对象

@GetMapping("/register")
public String getRegisterPage(ModelMap model) {
    Useruser = new User();
    model.put("user", user);
    return "register";
}

并且在您尝试加载 userData 对象的页面上

th:object="${userData}"

您需要将发送到页面的对象命名为 userData,或者在页面上使用名为 user..

的对象

喜欢:

@GetMapping("/register")
public String getRegisterPage(ModelMap model) {
    Useruser = new User();
    model.put("userData", user);
    return "register";
}

th:object="${user}"