How to User Registration Page in Spring Boot (Java)

How to Add User Registration Page in Spring Boot

This corresponds to Part 40 of our Complete Spring Boot Application (FleetMS) and we would create the user registration page. You will need to take the following 6 steps

  1. Create the Registration Page
  2. Update the Model and Database
  3. Write the ConfirmPassword Script
  4. Modify the Security Config
  5. Modify the addNew Method
  6. Add a Success Message
  7. Encode Your Password

Let’s dive right in!

 

Before you begin, you need to write the endpoint for /register.

 

Step 1: Create the Registration page

The easiest way to do this is to make a copy of the login page and name it register.html. Then add additional fields for Firstname, Lastname and ConfirmPassword.

Also remember to set the th:action to “/users/addNew”. As you already know, the method should be post.

Add a message placeholder using the code below

<span th:text="${message}"></span>

Then set the id of the password text field to password and the id of the confirmPassword field to confirmPassword

 

Step 2: Update the Model and Database

Now update the User.java class to include Firstname and Lastname fields

Run the application and check that these fields are created in the database

If not, then manually create them. This means, you need to open MySQL Command Prompt and write the queries.

Moreover, ensure that the id field is an auto_increment field.

 

Step 3: Write the Password Confirmation Script

Now we are going to write the JavaScript code to confirm that the passwords match.

Create a new file in the js folder called register.js.

Include the code below:

$('document').ready(function(){			
	var password = document.getElementById("password")
	var confirmPassword = document.getElementById("confirmPassword");
	
	function validatePassword(){
	  if(password.value != confirmPassword.value) {
	    confirmPassword.setCustomValidity("Passwords Don't Match");
	  } else {
	    confirmPassword.setCustomValidity('');
	  }
	}	
	password.onchange = validatePassword;
	confirmPassword.onkeyup = validatePassword;		
});

 

Step 4: Modify the SecurityConfiguration

Now we need to modify the security configuration to allow access to the register.html and register.js without authentication. Also we should allow access to the “/user/addNew” endpoint.

Open the ApplicationSecurityConfig.java file

Add an antMatcher() for “/register” and “/users/addNew”.

For the “/register” you need to allow access the the js folder by also adding “/js/**”.

So the addition to the file is as shown below:

.antMatchers("/register", 
		"/resources/**", 
		"/css/**", 
		"/fonts/**", 
		"/img/**", 
		"/js/**").permitAll()
.antMatchers("/users/addNew").permitAll()

 

Step 5: Modify the “addNew” Method

We now need to modify the method for saving a new user. This because, we want a successful user registration to redirect to the login page.

We would also display a message telling the user that the registration was successful and he can go on to login.

Open the UserController, change the addNew method to the one below:

//Modified method to Add a new user User
@PostMapping(value="users/addNew")
public RedirectView addNew(User user, RedirectAttributes redir) {
	userService.save(user);	
	RedirectView  redirectView= new RedirectView("/login",true);
        redir.addFlashAttribute("message",
    		"You successfully registered! You can now login");
    return redirectView;				
}	

Just to explain briefly what is happening here.

First we did not use Model and addAttributes. The reason is that, values in the model attributes are cleared after redirect.

Therefore, we make the method return a RedirectView instead of a string(view). Then we place a flashAttribute in the RedirectAttributes object. In this way, the value of the flash attribute is preserved when a redirect occurs.

 

Step 6: Add the Success Message

Since we need to redurect to the login page after registration, the success message will therefore be placed in the login page. But it shows only if a redirect occurs from the register page.

Open the login page.

Just below the opening <form> tag, add the following code:

<div style="text-align:center; font-size:20px; color:green; font-weight:bold">  
    <span th:utext="${message}"></span> 
</div>

 

Step 7: Encode the Password

Now we would encode the password using BCryptPasswordEncoder. Although there are other encoders, BCrypt offers a stronger encryption algorithm than most. We’ll do this in just three steps.

  • First, create a BCryptPasswordEncoder bean in the ApplicationSecurityConfig file. The bean is as shown below:
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
	return new BCryptPasswordEncoder();
}
  • Second, set providers encoder to use a BCryptPasswordEncoder type instead of NoOpPasswordEncoder
  • Third, open the UserService. Modify the save method such that before you save, you need to set the password. Use setPassword and then provide an encoded password.

Now you can test the application!