Create a login and registration in spring boot using JPA Repository and MYSQL. In this tutorial, let’s create a spring boot application from scratch to perform Login and Registration using JPA and MYSQL.
Login and registration steps in spring boot JPA and MYSQL
- Create a spring boot project using a spring boot initializr.
- Add required dependencies into pom.xml
- Configure application.properties
- Create Controller, Entity, and repository.
- Design login and registration page.
- Run the application and perform testing on it.
Create a spring boot project using a spring boot initializr.
Navigate to “https://start.spring.io/” and create a spring web project with the required dependencies. download the project and import it into your IDE. It’s a simple and easy process to get more details on it please follow the tutorial, How to Create Spring Boot project using Spring Initializr?
Add required dependencies into pom.xml
Open the pom.xml and add the below dependencies and plugins. that contains all the required dependencies to perform login and registration into spring boot.
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.7.2</version> <relativePath /> <!-- lookup parent from repository --> </parent> <groupId>com</groupId> <artifactId>ProductStore</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>MedicalStore</name> <description>Online Product Store Project in Spring boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency> <!-- Provided --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.tomcat</groupId> <artifactId>jsp-api</artifactId> <version>6.0.32</version> <scope>provided</scope> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> <type>jar</type> <scope>compile</scope> </dependency> <!-- Test --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <excludes> <exclude> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </exclude> </excludes> </configuration> </plugin> </plugins> </build> </project>
Configure application.properties
application.properties is a configuration file that contains many parameters in the below code as per requirement it contains database and context path configuration.
spring.datasource.url=jdbc:mysql://localhost:3306/productstore?createDatabaseIfNotExist=true spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.username=root spring.datasource.password=root spring.jpa.database-platform = org.hibernate.dialect.MySQL8Dialect spring.jpa.generate-ddl=true spring.jpa.hibernate.ddl-auto = update spring.mvc.view.prefix=/WEB-INF/jsp/ spring.mvc.view.suffix=.jsp server.servlet.context-path=/ProductStore
Create Controller, Entity, and repository.
WelcomePageCtl is a welcome page for the application, When we run the application and send a get request with the name “/welcomepage” from the URL then it will return welcome.jsp as a response.
package com.ProductStore.ctl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.env.Environment; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class WelcomePageCtl { @Autowired private Environment env; @GetMapping("/welcomepage") public String welcomePage() { return "welcome"; } }
UserLoginPageCtl
Create login controller that contains two methods loginPage() and LoginUser(), where the loginPage() will return the login.jsp as view and LoginUser() will perform the login activity.
package com.ProductStore.ctl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import com.ProductStore.entity.UserEntity; import com.ProductStore.repository.UserRepository; @Controller public class UserLoginPageCtl { @Autowired private UserRepository userRepository; @GetMapping("/loginPage") public String loginPage() { return "login"; } @PostMapping("/loginUser") public String loginUser(@ModelAttribute("form") UserEntity user, Model model) { user = userRepository.findByLoginAndPassword(user.getLogin(), user.getPassword()); if(user == null) { model.addAttribute("msg", "Invalid Login and Password"); return "login"; }else { return "redirect:/welcomepage"; } } }
UserRegPageCtl
Create a registration Controller that contains saveUser() that will get the data from the registration view and save the data into MYSQL database.
package com.ProductStore.ctl; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import com.ProductStore.entity.UserEntity; import com.ProductStore.repository.UserRepository; @Controller public class UserRegPageCtl { @Autowired private UserRepository userRepository; @GetMapping("/userRegPage") public String RegPage() { return "userRegistration"; } @PostMapping("/saveUser") public String saveUser(HttpServletRequest request, @ModelAttribute("form") UserEntity user , Model model){ userRepository.save(user); model.addAttribute("msg", "User Register Sucessfully"); System.out.println("User Controller"); return "userRegistration"; } }
User Entity
UserEntity is the java class that converts a user’s properties into an object also, it contains getter and setter and the same class will be mapped with the user table into the database,
package com.ProductStore.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import lombok.Getter; import lombok.Setter; @Entity @Getter @Setter @Table(name = "user") public class UserEntity { @Id @Column(name = "id" ) @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @Column(name = "firstname",length = 755) private String firstName; @Column(name = "lastname",length = 755) private String lastName; @Column(name = "email",length = 755) private String email; @Column(name = "phonenumber",length = 755) private String phoneNumber; @Column(name = "login",length = 755) private String login; @Column(name = "password",length = 755) private String password; @Override public String toString() { return "UserEntity [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + ", phoneNumber=" + phoneNumber + ", login=" + login + ", Password=" + password + "]"; } }
User Repository
User Repository is an interface that extends the JPA repository that helps to perform database transactions also it contains an abstract method called public UserEntity findByLoginAndPassword(String login, String Password); which will be implemented into the login controller to perform login operation.
package com.ProductStore.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.ProductStore.entity.UserEntity; public interface UserRepository extends JpaRepository<UserEntity, Long>{ public UserEntity findByLoginAndPassword(String login,String Password); }
Design login and registration page
welcome.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Welcome Page</title> <%@ include file="header.jsp" %> </head> <body> <h1>Welcome</h1> </body> </html>
header.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@taglib uri="http://www.springframework.org/tags" prefix="s"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@page isELIgnored="false"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-secondary"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> <li class="nav-item active"> <a class="nav-link" href="${pageContext.request.contextPath}/welcomepage">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="${pageContext.request.contextPath}/loginPage">Login</a> </li> <li class="nav-item"> <a class="nav-link" href="${pageContext.request.contextPath}/userRegPage">SingUp</a> </li> </ul> </div> </nav>
login.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Login Page</title> <%@ include file="header.jsp" %> </head> <body> <main class="login-form"> <div class="cotainer"> <div class="row justify-content-center"> <div class="col-md-8"> <div class="card"> <div class="card-header"> Login </div> <div class="card-body"> <h3 class="text-danger">${msg}</h3> <form action="${pageContext.request.contextPath}/loginUser" method="post" modelattribute="form"> <div class="form-group row"> <label for="email_address" class="col-md-4 col-form-label text-md-right">Login Id<font color="red">*</font></label> <div class="col-md-6"> <input type="text" id="login" class="form-control" placeholder="Enter Login Id" name="login" value="" > <font color="red"></font> </div> </div> <div class="form-group row"> <label for="password" class="col-md-4 col-form-label text-md-right">Password<font color="red">*</font></label> <div class="col-md-6"> <input type="password" id="password" class="form-control" placeholder="Enter Password" name="password" value="" > <font color="red"> </font> </div> </div> <div class="col-md-6 offset-md-4"> <input type="submit" class="btn btn-primary" name="operation" value="Login"> </div> </form> </div> </div> </div> </div> </div> </main> </body> </html>
userRegistration.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Sing Up</title> <%@ include file="header.jsp" %> </head> <body> <main class="login-form"> <div class="cotainer"> <div class="row justify-content-center"> <div class="col-md-8"> <div class="card"> <div class="card-header"> User Registration </div> <div class="card-body"> <h3 class="text-success">${msg}</h3> <form action="${pageContext.request.contextPath}/saveUser" method="post" modelattribute="form"> <div class="form-group row"> <label for="email_address" class="col-md-4 col-form-label text-md-right">First Name<font color="red"></font></label> <div class="col-md-6"> <input type="text" class="form-control" placeholder="Enter First Name" name="firstName" value="" > <font color="red"></font> </div> </div> <div class="form-group row"> <label for="email_address" class="col-md-4 col-form-label text-md-right">Last Name<font color="red"></font></label> <div class="col-md-6"> <input type="text" class="form-control" placeholder="Enter Last Name" name="lastName" value="" > <font color="red"></font> </div> </div> <div class="form-group row"> <label for="email_address" class="col-md-4 col-form-label text-md-right">Email<font color="red"></font></label> <div class="col-md-6"> <input type="text" class="form-control" placeholder="Enter email" name="email" value="" > <font color="red"></font> </div> </div> <div class="form-group row"> <label for="email_address" class="col-md-4 col-form-label text-md-right">Login Id<font color="red"></font></label> <div class="col-md-6"> <input type="text" id="email_address" class="form-control" placeholder="Enter Login Id" name="login" value="" > <font color="red"></font> </div> </div> <div class="form-group row"> <label for="email_address" class="col-md-4 col-form-label text-md-right">Password<font color="red"></font></label> <div class="col-md-6"> <input type="password" id="email_address" class="form-control" placeholder="Enter password" name="password" value="" > <font color="red"></font> </div> </div> <div class="form-group row"> <label for="email_address" class="col-md-4 col-form-label text-md-right">Mobile No.<font color="red"></font></label> <div class="col-md-6"> <input type="text" id="email_address" class="form-control" placeholder="Enter Mobile No" name="mobile" value="" > <font color="red"></font> </div> </div> <div class="col-md-6 offset-md-4"> <input type="submit" class="btn btn-primary" name="operation" value="Register"> </div> </form> </div> </div> </div> </div> </div> </main> </body> </html>