Home > Blockchain >  Neither BindingResult nor plain target object for bean name 'userData' available as reques
Neither BindingResult nor plain target object for bean name 'userData' available as reques

Time:06-03

I am trying to follow this to display some error messages for the user when trying to register and not entering the correct input or leaving the input empty. I am getting in the console the error in the title and the page display this error message There was an unexpected error (type=Internal Server Error, status=500).

I have a class User that does not implement Serializable and exactly like the 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 >
  <div >
    <div >
      <div >
        <p >Register a new account</p>

        <form action="#" th:action="@{/register}" th:object="${userData}" method="post">
          <div  th:if="${#fields.hasErrors('*')}">
          <p th:each="err : ${#fields.errors('*')}" th:text="${err}"></p>
        </div>
        </form>
        <div >
        <input type="text"   th:field="*{firstName}" placeholder="First Name" th:error>
        <div >
          <div >
            <span ></span>
          </div>
        </div>
      </div>
        <div >
          <input type="text"   th:field="*{lastName}" placeholder="Last Name" th:error>

          <div >
            <div >
              <span ></span>
            </div>
          </div>
        </div>
       <div >
          <input type="email"  th:field="*{email}" placeholder="Email" th:error>

          <div >
            <div >
              <span ></span>
            </div>
          </div>
        </div>
         <div >
          <input type="text"  th:field="*{username}" placeholder="username" th:error>

          <div >
            <div >
              <span ></span>
            </div>
          </div>
        </div>
        
        <div >
          <input type="password"  th:field="*{password}" placeholder="Password" th:error>

          <div >
            <div >
              <span ></span>
            </div>
          </div>
        </div>
        
        
    </div>
    <!-- /.form-box -->
  </div><!-- /.card -->
</div>

</body>

</html>

CodePudding user response:

when opening the register page you are sending the user object

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

and on the page you are trying to load the userData object

th:object="${userData}"

you need that the object sent to the page, be named userData, or on the page use the object named user..

like:

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

or

th:object="${user}"
  • Related