0% found this document useful (0 votes)
3 views58 pages

Java lab file 2.0

The document outlines various Java programming exercises, including using Eclipse for Java development, command-line arguments, OOP concepts, inheritance, polymorphism, exception handling, multithreading, Java packages, and I/O operations. It provides detailed steps and code examples for each topic, demonstrating how to implement these concepts in Java. Additionally, it introduces a project for creating a user registration and login module using the Spring Framework, highlighting the tools and technologies involved.

Uploaded by

iec.vineet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views58 pages

Java lab file 2.0

The document outlines various Java programming exercises, including using Eclipse for Java development, command-line arguments, OOP concepts, inheritance, polymorphism, exception handling, multithreading, Java packages, and I/O operations. It provides detailed steps and code examples for each topic, demonstrating how to implement these concepts in Java. Additionally, it introduces a project for creating a user registration and login module using the Spring Framework, highlighting the tools and technologies involved.

Uploaded by

iec.vineet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

Program 1

Objective: Use Java Compiler and Eclipse platform to write and execute java program.

Related Theory: Eclipse is the most popular IDE for Java application development. In 2001, IBM formed a
consortium to support the development of Eclipse IDE. In 2004, it become the Eclipse Foundation whose main
vision was to guide, implement, and share the development of open-source (software whose source code is
released under a license) Eclipse projects in a vendor-natural environment. It is an open-source Integrated
Development Environment (IDE). It is written in Java. It is used to develop Java applications (Java SE and Java EE). It
is also used to develop applications in other languages, such as C, C++, PHY, Python, Perl, and other web projects
with the help of extensible plug-ins. We can run it on different platforms, like Windows, Linux, and macOS.
Presently, it is the widely used IDE for developing Java applications.

Here are the steps on how to write and execute a Java program using the Java compiler and Eclipse platform:

1. Open Eclipse.

2. Create a new Java project.

3. Create a new class in the project.

4. Write your Java code in the class file.

5. Save the class file.

6. Compile the Java code using the Java compiler.

7. Execute the Java program.

Here are some more details about each step:

1. To open Eclipse, double-click on the Eclipse icon on your desktop.

2. To create a new Java project, select File > New > Java Project.

3. In the New Java Project dialog, enter a name for your project and click Finish.

4. To create a new class in the project, right-click on the project name in the Package Explorer and select New
> Class.

5. In the New Java Class dialog, enter a name for your class and select the public static void main(String[] args)
checkbox. Click Finish.

6. Write your Java code in the class file.

7. To save the class file, click the Save button on the toolbar.

8. To compile the Java code, click the Run button on the toolbar.

9. To execute the Java program, click the Run button on the toolbar.
Program Code:

public class HelloWorld

public static void main(String args[])

System.out.println(“Hello World!”);

Output:
Program: 2

Objective: Creating simple java programs using command line arguments.

Related Theory: What Are Command Line Arguments?

The command-line arguments are passed to the program at run-time. Passing command-line arguments in a Java
program is quite easy. They are stored as strings in the String array passed to the args parameter of main() method
in Java.

To compile and run a java program in command prompt follow the steps written below.

• Save your program in a file with a .java extension

• open the command prompt and go to the directory where your file is saved.

• Run the command – javac filename.java

• After the compilation run the command – java filename

• Make sure the Java path is set correctly.

Program Code:

class Multvalue

public static void main(String args[])

System.out.println("This is muliple command line argument");

for(String value: args)

System.out.println(value);

}
Output:
Program: 3

Objective: Understand OOP concepts and basics of Java Programming .


Related Theory:

 Abstraction:
Abstraction is the process of hiding the implementation details of an object and exposing only its
essential features. This allows us to focus on what an object does, rather than how it does it.
 Encapsulation:
Encapsulation is the process of wrapping data and code together into a single unit, called a class. This
protects the data from being accessed or modified in unintended ways.
 Inheritance:
Inheritance is the process of creating a new class that inherits the properties and methods of an existing
class. This allows us to reuse code and create hierarchies of classes.
 Polymorphism:
Polymorphism is the ability of an object to take on many different forms. This allows us to write code
that can work with different types of objects without having to know the specific type of object at
compile time.

Here are some of the basics of Java programming:

 Java is a class-based language:


This means that all code in Java is organized into classes. A class is a blueprint for creating objects.

 Java is an object-oriented language:


This means that Java programs are made up of objects that interact with each other.

 Java is a platform-independent language:


This means that Java code can run on any platform that has a Java Virtual Machine (JVM).

 Java is a compiled language:


This means that Java code is converted into bytecode before it is executed. Bytecode is a platform-
independent intermediate representation of Java code.

Here are some of the benefits of using OOP in Java:

 OOP makes code more modular and reusable:


We can break down our code into smaller, more manageable pieces by using classes. This makes our
code easier to understand, maintain, and reuse.
 OOP makes code more extensible:
We can extend the functionality of our code by creating new classes that inherit from existing classes.
This allows us to add new features to our code without having to rewrite the existing code.
 OOP makes code more secure:
We can protect our data from being accessed or modified in unintended ways by using encapsulation.
This makes our code more secure and reliable.
Program: 4
Objective: Create Java programs using Inheritance and polymorphism .
Related Theory:

Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent
object. It is an important part of OOPs (Object Oriented programming system).

The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When
you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add
new methods and fields in your current class also. Inheritance represents the IS-A relationship which is also
known as a parent-child relationship.

Polymorphism in Java is a concept by which we can perform a single action in different ways. Polymorphism is
derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So
polymorphism means many forms.

There are two types of polymorphism in Java: compile-time polymorphism and runtime polymorphism. We can
perform polymorphism in java by method overloading and method overriding.

Program Code:

class Area

void area(int r)

System.out.println("Area f circle is : " +(3.14*r*r));

void area(int l, int w)

System.out.println("area of rectangle is : " + (l*w));

public static void main(String args[])

Area obj = new Area();

obj.area(100); //compile time polymorphism

obj.area(20,30);

Output:

Compile-time polymorphism
Program Single-Level Inheritance:
class Employee
{
float salary=40000;

class Programmer extends Employee


{

int bonus=10000;

public static void main(String args[])


{
Programmer p = new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);

Output:
Program 5
Objective: Implement error-handling techniques using exception handling
and multithreading.
Related Theory: exception handling
Exception Handling in Java is one of the effective means to handle runtime errors so that the regular flow of the
application can be preserved. Java Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Exception handling in java helps in minimizing exceptions and helps in recovering from exceptions. It is one of the
powerful mechanisms to handle runtime exceptions and makes it bug-free. Exception handling helps in
maintaining the flow of the program. An exception handling is defined as an abnormal condition that may happen
at runtime and disturb the normal flow of the program.

Exception : An expectation is an unexpected event that occurs while executing the program, that disturbs the
normal flow of the code.

Types of exception in Java

8. Checked Exceptions

1. Those exceptions that are checked at compile-time comprises checked exceptions.

2. They are child classes of Exception except for RuntimeException.

3. The program will not compile if they are not handled.

4. Example: IOException, ClassNotFoundException, etc.

9. Unchecked Exceptions

1. Those exceptions that are checked at runtime comprises unchecked exceptions.

2. They are child classes of RuntimeException.

3. They give runtime errors if not handled explicitly.

4. Example: ArithmeticException, NullPointerException etc.

10. Java Exception Keywords


Exception Handling in java is managed via five keywords: try, catch, throw, throws, and finally. Here are 5
keywords that are used in handling exceptions in Java

Keyword Description

This keyword is used to specify a block and this block must be followed by either catch
try
or finally. That is, we can’t use try block alone.
This keyword must be preceded by a try block to handle the exception and can be
catch
followed by a final block later.

finally This keyword is used to execute the program, whether an exception is handled or not.

throw This keyword is used to throw an exception.

throws This keyword is used to declare exceptions.

Related Theory: - Multithreading

Multithreading in Java is a process of executing multiple threads simultaneously. A thread is a lightweight sub-
process, the smallest unit of processing. Multiprocessing and multithreading, both are used to achieve
multitasking. However, we use multithreading than multiprocessing because threads use a shared memory area.
They don't allocate separate memory area so saves memory, and context-switching between the threads takes
less time than process. Java Multithreading is mostly used in games, animation, etc.

Advantages of Java Multithreading

1) It doesn't block the user because threads are independent and you can perform multiple operations at the same
time.

2) You can perform many operations together, so it saves time.

3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.

Thread :A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of execution.
Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It uses a shared
memory area.
Program: Exception handling
package exceptionhandlingex;
public class exceptionexample
{
public static void main(String[] args)
{
try {
int x = 10;
int y = 0;
int z = x / y;
}
catch (ArithmeticException e)
{
System.out.println("Arithmetic exception!");
}
System.out.println("Please check the Parameters");
} }

Output:
Program: Multithreading
package multi;
class MultithreadingDemo extends Thread {
public void run()
{
try {

System.out.println(
"Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e) {
System.out.println("Exception is caught");
}
}
}

public class Multithread {


public static void main(String[] args)
{
int n = 8;
for (int i = 0; i < n; i++) {
MultithreadingDemo object
= new MultithreadingDemo();
object.start();
}
}
}
Output:
Program 6
Objective: Create java program with the use of java packages
Related Theory: Package in Java is a mechanism to encapsulate a group of classes, sub-packages, and interfaces.
All we need to do is put related classes into packages. After that, we can simply write an import class from existing
packages and use it in our program. A package is a container of a group of related classes where some classes are
accessible or exposed and others are kept for internal purposes. We can reuse existing classes from the packages
as many times as we need them in our program. Package names and directory structure are closely related

Ways: There are two types of packages in java:

10. User-defined Package (Create Your Own Package’s)

11. Built-in packages are packages from the java application programming interface that are the packages
from Java API for example such as swing, util, net, io, AWT, lang, javax, etc.

Program:

package package1;
import java.util.Scanner;

public class packagedemo {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Get the user's name
System.out.println("What is your name?");
String name = scanner.nextLine();
// Print a greeting to the user
System.out.println("Hello, " + name + "!");
// Close the scanner
scanner.close();
}
}
Output:
Program 7

Objective: Construct java program using Java I/O package.


Related Theory: Java I/O (Input and Output) is used to process the input and produce the output.

Java uses the concept of a stream to make I/O operation fast. The java.io package contains all the classes required
for input and output operations.

We can perform file handling in Java by Java I/O API.

The below program creates a File object, then creates a FileWriter object to write some data to the file. It then
closes the FileWriter object. Next, it creates a FileReader object to read the data from the file, and prints it to the
console. Finally, it closes the FileReader object.

Program:

import java.io.*;

public class JavaIOExample {

public static void main(String[] args) throws IOException {

// Create a File object


File file = new File("myFile.txt");

// Create a FileWriter object


FileWriter writer = new FileWriter(file);

// Write some data to the file


writer.write("This is some data that I am writing to the file.");

// Close the FileWriter object


writer.close();

// Create a FileReader object


FileReader reader = new FileReader(file);

// Read the data from the file


int i;
while ((i = reader.read()) != -1) {
System.out.print((char) i);
}

// Close the FileReader object


reader.close();
}
}
Output:
Experiment No. 8
User Registration and Login Form
Aim: Create industry oriented application using Spring Framework.

In this tutorial, we discuss how to create a Spring Boot User Registration and Login Module using Spring
Boot 3, Spring Security 6, Hibernate, and Thymeleaf.

In Spring Security 5.7.0-M2, the WebSecurityConfigurerAdapter class is deprecated, and the Spring team
encourages users to move towards a component-based security configuration.

we will use a new component-based security configuration approach.

Spring Security is a framework that provides authentication, authorization, and protection against common
attacks. With first-class support for securing imperative and reactive applications, it is the de-facto
standard for securing Spring-based applications.

Tools and Technologies Used:

In this tutorial, we will use the latest version of all the tools and technologies:

- Spring Boot 3
- Spring MVC 6
- Spring Security 6
- Hibernate 6
- Thymeleaf 3
- MySQL 8
- Maven
We validate the user registration fields with Java bean validation annotations and Hibernate validator
implementation.

Basically, we will develop a simple User Registration Module using Role-based Spring Security that can be
used in any Spring MVC-based project.

Let's get started with our objective. What will we build?

What will we build?

We will build two main functionalities:

1. Register a user (stored data in MySQL database).


2. Login Authentication - validate user login credentials with database email and password.
3. We will secure the Registered Users Page with role-based Spring Security.
User Registration Page:
Registered Users Page:

1. Create a SpringBoot Project.

Spring Boot provides a web tool called Spring Initializer to quickly bootstrap an application. To use
it, go to https://start.spring.io/ and generate a new Spring Boot project.
Use the below details in the Spring boot creation: Generate: Maven Project
Java Version: 17
Spring Boot: 3.0.0
Group: net.guides.springboot
Artifact: registration-login-demo Name: registration-login-demo
Dependencies: Web, JPA, MySQL, Thymeleaf, Security, Lombok

<?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>
-------
</parent>
<groupId>com.example</groupId>
<artifactId>registration-login-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>registration-login-demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>

2. Create a Project Structure or Packing Structure


Create packaging structure as per the screenshot below:

3. Configure MySQL database

Let's use the MySQL database to store and retrieve the data in this
example, and we gonna use Hibernate properties to create and drop
tables.
Open the application.properties file and add the following configuration
to it:
spring.datasource.url=jdbc:mysql://localhost:3306/login_system
spring.datasource.username=root spring.datasource.password=Mysql@123
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLD ialect
spring.jpa.hibernate.ddl-auto=update
Ensure you create a login_system database before running the Spring boot application.
Also, change the MySQL username and password as per the MySQL installation on your
machine.

4. Create JPA Entities - User and Role


Let's create User and Role JPA entities and establish a many-to-many mapping between them -
one user can have multiple roles, and one role can be assigned to multiple users.

The @ManyToMany JPA annotation is used to link the source entity with the target entity.
A many-to-many association always uses an intermediate join table to store the association that
joins two entities. The join table is defined using the @JoinTable JPA annotation.

USER:-

package com.example.registrationlogindemo.entity;

import jakarta.persistence.*; import lombok.AllArgsConstructor; import lombok.Getter;

import lombok.NoArgsConstructor; import lombok.Setter;

import java.util.ArrayList; import java.util.List;

@Getter @Setter

@NoArgsConstructor @AllArgsConstructor @Entity @Table(name="users") public class User

private static final long serialVersionUID = 1L;

@Id

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

@Column(nullable=false) private String name;

@Column(nullable=false, unique=true) private String email;

@Column(nullable=false) private String password;

@ManyToMany(fetch = FetchType.EAGER, cascade=CascadeType.ALL) @JoinTable(

name="users_roles",
@ManyToMany(mappedBy="roles") private List<User> users;
}
This above code defines a Java class called Role that is mapped to a database table
called roles. The class has several annotations on it:
@Getter and @Setter: These annotations are from the Lombok library and automatically
generate getter and setter methods for all of the class's fields.
@NoArgsConstructor: This annotation is from Lombok and generates a no-argument
constructor for the class.
@AllArgsConstructor: This annotation is from Lombok and generates a constructor that takes
arguments for all of the class's fields.
@Entity: This annotation is from the Java Persistence API (JPA) and specifies that the class
is a JPA entity, meaning that it is mapped to a database table.
@Table(name="users"): This annotation is from JPA and specifies the name of the database
table that the entity is mapped to.
@Id: This annotation is from JPA and specifies that the field id is the primary key for the
database table.
@GeneratedValue(strategy = GenerationType.IDENTITY): This annotation is from JPA and specifies
that the primary key values are automatically generated by the database using an identity column.

5. Create UserRepository and RoleRepository


Next, let's create Spring Data JPA repositories for User and Role JPA Entities
UserRepository
package net.javaguides.springboot.repository; import net.javaguides.springboot.entity.User;
import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends
JpaRepository<User, Long> {
User findByEmail(String email);

}
The above code defines a Spring Data JPA repository interface called UserRepository, which extends the
JpaRepository interface. The JpaRepository interface provides several methods for performing CRUD (Create,
Read, Update, Delete) operations on a JPA entity. It takes two type parameters: the entity type, User, and the type
of the entity's primary key, Long.
In addition to the methods provided by JpaRepository, the UserRepository interface also declares a custom
method called findByEmail(). This method uses Spring Data JPA's method name query creation feature to generate
a query that finds a user by their email address. The method takes a single argument, which is the email address to
search for, and it returns a User object if a match is found or null otherwise

RoleRepository:-
package net.javaguides.springboot.repository; import
net.javaguides.springboot.entity.Role;
import org.springframework.data.jpa.repository.JpaRepository; public interface
RoleRepository extends JpaRepository<Role, Long> {
Role findByName(String name);
}
The above code defines a Spring Data JPA repository interface called RoleRepository,
which extends the JpaRepository interface. The JpaRepository interface provides
several methods
for performing CRUD (Create, Read, Update, Delete) operations on a JPA entity. It
takes two type parameters: the entity type, Role, and the type of the entity's primary
key, Long.
In addition to the methods provided by JpaRepository, the RoleRepository interface
also declares a custom method called findByName(). This method uses Spring Data
JPA's method name query creation feature to generate a query that finds a role by its
name. The method takes a single argument, which is the role name to search for, and
it returns a Role object if a match is found or null otherwise.

6. Create a Thymeleaf Template for the Home Page.


Let's create an AuthController Spring MVC controller class and add the following content

package net.javaguides.springboot.controller; import org.springframework.stereotype.Controller; import


org.springframework.ui.Model;

import org.springframework.web.bind.annotation.GetMapping;

@Controller

public class AuthController {

// handler method to handle home page request @GetMapping("/index")

public String home(){ return "index";

The above code defines a Spring MVC controller class called AuthController, which handles incoming
requests to the /index URL path. The @Controller annotation indicates that this class is a Spring MVC
controller and should be scanned by the Spring framework to handle incoming requests. The
@GetMapping("/index") annotation on the home() method maps

HTTP GET requests to the /index URL path to this method. When a user makes a GET request to this URL
path, the home() method is executed. This method returns the String "index", the name of a view template
that will be resolved by the Spring framework's view resolver.

Thymeleaf Template - Index.html

Next, let's create an index Thymeleaf template view. Note that we use bootstrap CSS CDN links below the
Thymeleaf HTML page.

<!DOCTYPE html>

<html lang="en" xmlns:th="http://www.thymeleaf.org"

>

<head>

<meta charset="UTF-8">

<title>Registration and Login System</title>

<link

href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"


integrity="sha384- EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"

crossorigin="anonymous">

</head>

<body>

<nav class="navbar navbar-expand-lg navbar-dark bg-dark">

<div class="container-fluid">

<a class="navbar-brand" th:href="@{/index}">Registration and Login System</a>

<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data- bs-


target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria- expanded="false" aria-
label="Toggle navigation">

<span class="navbar-toggler-icon"></span>

</button>

<div class="collapse navbar-collapse" id="navbarSupportedContent">

<ul class="navbar-nav me-auto mb-2 mb-lg-0">

<li class="nav-item">

<a class="nav-link active" aria-current="page" th:href="@{/register}">Register</a>

</li>

</ul>

</div>

</div>

</nav>

<br /><br />

<div class="container">

<div class="row">

<h1 class="text-center"> Registration and Login System </h1>

</div>

</div>

</body>

</html>

7. Create a Service Layer


UserService Interface

package net.javaguides.springboot.service;

import net.javaguides.springboot.dto.UserDto;
import net.javaguides.springboot.entity.User;

import java.util.List;

public interface UserService { void saveUser(UserDto userDto);

User findUserByEmail(String email);

List<UserDto> findAllUsers();

UserServiceImpl class:-

Let's define a Spring service class called UserServiceImpl that implements

the UserService interface. The @Service annotation indicates that this class is a Spring service that should
be scanned by the Spring framework for dependency injection

package net.javaguides.springboot.service.impl;

import net.javaguides.springboot.dto.UserDto; import net.javaguides.springboot.entity.Role; import


net.javaguides.springboot.entity.User;

import net.javaguides.springboot.repository.RoleRepository; import


net.javaguides.springboot.repository.UserRepository; import
net.javaguides.springboot.service.UserService;

import org.springframework.security.crypto.password.PasswordEncoder; import


org.springframework.stereotype.Service;

import java.util.Arrays; import java.util.List;

import java.util.stream.Collectors;

@Service

public class UserServiceImpl implements UserService {

private UserRepository userRepository; private RoleRepository roleRepository; private PasswordEncoder


passwordEncoder;

public UserServiceImpl(UserRepository userRepository,

RoleRepository roleRepository, PasswordEncoder passwordEncoder) {

this.userRepository = userRepository; this.roleRepository = roleRepository; this.passwordEncoder =


passwordEncoder;

@Override

public void saveUser(UserDto userDto) { User user = new User();

user.setName(userDto.getFirstName() + " " + userDto.getLastName()); user.setEmail(userDto.getEmail());

// encrypt the password using spring security


user.setPassword(passwordEncoder.encode(userDto.getPassword()));
Role role = roleRepository.findByName("ROLE_ADMIN"); if(role == null){

role = checkRoleExist();

user.setRoles(Arrays.asList(role)); userRepository.save(user);

@Override

public User findUserByEmail(String email) { return userRepository.findByEmail(email);

@Override

public List<UserDto> findAllUsers() { List<User> users = userRepository.findAll(); return users.stream()

.map((user) -> mapToUserDto(user))

.collect(Collectors.toList());

private UserDto mapToUserDto(User user){ UserDto userDto = new UserDto(); String[] str =
user.getName().split(" "); userDto.setFirstName(str[0]); userDto.setLastName(str[1]);
userDto.setEmail(user.getEmail()); return userDto;

private Role checkRoleExist(){ Role role = new Role(); role.setName("ROLE_ADMIN");

return roleRepository.save(role);

}}

The UserServiceImpl class implements the UserService interface, which defines several methods for
working with users. These methods include:

saveUser(UserDto userDto): This method creates a new User Entity and saves it to the database.

findUserByEmail(String email): This method finds a user in the database by their email address. It takes an
email address as input and returns the corresponding User entity if it exists.

findAllUsers(): This method retrieves a list of all users from the database and maps each User entity to a
UserDto object, which contains only the user's name and email address.

8. Create UserDto Model Class


We use UserDto class to transfer the data between the controller layer and the view layer.
We also use UserDto class for form binding.

package com.example.registrationlogindemo.dto;
import jakarta.validation.constraints.Email; import jakarta.validation.constraints.NotEmpty; import
lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor; import lombok.Setter;
@Getter @Setter
@NoArgsConstructor @AllArgsConstructor public class UserDto
{
private Long id; @NotEmpty
private String firstName;
@NotEmpty
private String lastName;
@NotEmpty(message = "Email should not be empty") @Email
private String email;
@NotEmpty(message = "Password should not be empty") private String password;
}

9. User Registration Feature Implementation:-


Let's first add a handler method in AuthController to handle User registration requests:
package net.javaguides.springboot.controller;

import jakarta.validation.Valid;

import net.javaguides.springboot.dto.UserDto; import org.springframework.stereotype.Controller; import


org.springframework.ui.Model;

import org.springframework.web.bind.annotation.GetMapping;

@Controller

public class AuthController {

// handler method to handle home page request @GetMapping("/index")

public String home(){ return "index";

// handler method to handle user registration form request @GetMapping("/register")

public String showRegistrationForm(Model model){

// create model object to store form data UserDto user = new UserDto(); model.addAttribute("user", user);

return "register";

}}

Next, let's create a register.html Thymeleaf template and design a User Registration form:
<!DOCTYPE html>

<html lang="en" xmlns:th="http://www.thymeleaf.org"

>

<head>

<meta charset="UTF-8">

<title>Registration and Login System</title>

<link

href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"

integrity="sha384- EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"

crossorigin="anonymous">

</head>
</div>

</body>

</html>

Next, let's create a handler method to save user registration data in the MySQL database.

package net.javaguides.springboot.controller;

import jakarta.validation.Valid;

import net.javaguides.springboot.dto.UserDto; import net.javaguides.springboot.entity.User;

import net.javaguides.springboot.service.UserService; import org.springframework.stereotype.Controller;


import org.springframework.ui.Model;

import org.springframework.validation.BindingResult; import


org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.ModelAttribute; import


org.springframework.web.bind.annotation.PostMapping;

import java.util.List;

@Controller

public class AuthController { private UserService userService;

public AuthController(UserService userService) { this.userService = userService;

// handler method to handle home page request @GetMapping("/index")

public String home(){ return "index";

// handler method to handle user registration form request @GetMapping("/register")

public String showRegistrationForm(Model model){

// create model object to store form data UserDto user = new UserDto(); model.addAttribute("user", user);

return "register";

// handler method to handle user registration form submit request @PostMapping("/register/save")

public String registration(@Valid @ModelAttribute("user") UserDto userDto, BindingResult result,

Model model){

User existingUser = userService.findUserByEmail(userDto.getEmail());

if(existingUser != null && existingUser.getEmail() != null &&

!existingUser.getEmail().isEmpty()){

result.rejectValue("email", null,
"There is already an account registered with the same email");

if(result.hasErrors()){ model.addAttribute("user", userDto); return "/register";

userService.saveUser(userDto); return "redirect:/register?success";

}}

10. Display List Registered Users

Next, let's create a handler method in AuthController to handle Get Registered Users
requests from the MySQL database.
// handler method to handle list of users @GetMapping("/users")

public String users(Model model){

List<UserDto> users = userService.findAllUsers(); model.addAttribute("users", users);

return "users";

Here is the complete code for AuthController

package net.javaguides.springboot.controller;

import jakarta.validation.Valid;

import net.javaguides.springboot.dto.UserDto; import net.javaguides.springboot.entity.User;

import net.javaguides.springboot.service.UserService; import org.springframework.stereotype.Controller; import


org.springframework.ui.Model;

import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.ModelAttribute; import


org.springframework.web.bind.annotation.PostMapping;

import java.util.List;

@Controller

public class AuthController { private UserService userService;

public AuthController(UserService userService) { this.userService = userService;

// handler method to handle home page request @GetMapping("/index")

public String home(){ return "index";

}
<td th:text = "${user.email}"></td>

</tr>

</tbody>

</table>

</div>

</body>

</html>

11. Create a Custom Login Form

Let's create a handler method to handle login requests in AuthController:


<!DOCTYPE html>

<html lang="en" xmlns:th="http://www.thymeleaf.org"

>

<head>

<meta charset="UTF-8">

<title>Registration and Login System</title>

<link

href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"

integrity="sha384- EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"

crossorigin="anonymous">

</head>

<body>

<nav class="navbar navbar-expand-lg navbar-dark bg-dark">

<div class="container-fluid">

<a class="navbar-brand" th:href="@{/index}">Registration and Login System</a>

<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data- bs-target="#navbarSupportedContent" aria-


controls="navbarSupportedContent" aria- expanded="false" aria-label="Toggle navigation">

<span class="navbar-toggler-icon"></span>

</button>

<div class="collapse navbar-collapse" id="navbarSupportedContent">

<ul class="navbar-nav me-auto mb-2 mb-lg-0">

<li class="nav-item">

<a class="nav-link active" aria-current="page" th:href="@{/register}">Register</a>

</li>

</ul>

</div>

</div>
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeHttpRequests((authorize) ->
authorize.requestMatchers("/register/**").permitAll()
.requestMatchers("/index").permitAll()
.requestMatchers("/users").hasRole("ADMIN")
).formLogin(
form -> form
.loginPage("/login")
.loginProcessingUrl("/login")
.defaultSuccessUrl("/users")
.permitAll()
).logout(
logout -> logout
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.permitAll()
);
return http.build();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
}}
@EnableWebSecurity annotation is used to enable Spring Security’s web security
support and provide the Spring MVC integration.
The BCryptPasswordEncoder implementation uses the widely supported bcrypt
algorithm to hash the passwords.

13. Database Authentication Implementation

We are implementing database authentication, so let's load the User from the database
CustomUserDetailsService

Let's create a CustomUserDetailsService class with the following content:

package com.example.registrationlogindemo.security;

import com.example.registrationlogindemo.entity.Role; import


com.example.registrationlogindemo.entity.User;

import com.example.registrationlogindemo.repository.UserRepository; import


org.springframework.security.core.GrantedAuthority;

import org.springframework.security.core.authority.SimpleGrantedAuthority;

import org.springframework.security.core.userdetails.UserDetails; import


org.springframework.security.core.userdetails.UserDetailsService;

import org.springframework.security.core.userdetails.UsernameNotFoundException; import


org.springframework.stereotype.Service;

import java.util.Collection; import java.util.stream.Collectors;

@Service

public class CustomUserDetailsService implements UserDetailsService { private


UserRepository userRepository;

public CustomUserDetailsService(UserRepository userRepository) { this.userRepository =


userRepository;

@Override

public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {

User user = userRepository.findByEmail(email);

if (user != null) { return new

org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(),
mapRolesToAuthorities(user.getRoles()));

}else{

throw new UsernameNotFoundException("Invalid username or password.");

}}

private Collection < ? extends GrantedAuthority> mapRolesToAuthorities(Collection

<Role> roles) {

Collection < ? extends GrantedAuthority> mapRoles = roles.stream()

.map(role -> new SimpleGrantedAuthority(role.getName()))

.collect(Collectors.toList()); return mapRoles;


}}

14. DEMO

Let's run the spring boot application using the main entry point class and have a
demo.
Let's access the http://localhost:8080/ link from the browser, which will result in
the home page

Click on the Register link to navigate to the Registration page:


Experiment No. 9
RESTful Web Services
Aim: Test RESTful web services using Spring Boot.

Let's take a look at a tutorial that explains all of the REST calls: GET, POST,
PUT, and DELETE.
Let’s start this project step by step.

Prerequisites for this project:

If you have Eclipse, download the STS plug-in from here.

If you don’t have Eclipse, download STS from here.

Download the latest JDK from here.

Also for testing please download and install SOAPUI tool from here.

The first example I am going to explain is about HTTP GET request, the second example will
be about HTTP POST request, the third example about HTTP PUT request, and the fourth
example is for HTTP DELETE request. In all of these examples, I am going to use JSON
Representation.

You can download this project from here.

1. First, create a folder in your C drive: C:\Projects

2. Open eclipse and select work space as: C:\Projects

3. From the File menu, select "New" and then "other," and from wizard, expand "Spring Boot"
and select "Spring Starter Project" (File->New->other->wizard->Spring Starter Project).

1/30
Now click the Next button and provide the below information and click the Next button
again.

2/30
Now, provide/select the below information and

click the Finish button.

Now you can see the below project structure in your project's explorer window.

3/30
4/30
Now, look that the SpringBootRest2Application.java file, which is created by the STS
plug-ins.

package com.bhaiti.kela.server.main;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootRest2Application {

public static void main(String[] args) {


SpringApplication.run(SpringBootRest2Application.class, args);
}
}

This is a Spring Boot main class. A Spring Boot REST application loads through this class.
We can also see that this class is created with the annotation @SpringBootApplication . As
per the Spring documentation, the annotation @SpringBootApplication is equivalent to
using @Configuration, @EnableAutoConfiguration, and @ComponentScan, and these
annotations are frequently used together. Most of the time, in Spring Boot development, the
main class is always annotated with all three of these important annotations.

5/30
So we are going to modify the @SpringBootApplication (given below in the Java class)
with a component path. Without that, the application cannot find out the controller classes.
We will learn more about controller classes in a few minutes.

@SpringBootApplication(scanBasePackages = {"com.bhaiti"})

@SpringBootApplication(scanBasePackages = {"com.bhaiti"})
public class SpringBootRest2Application {

public static void main(String[] args) {


SpringApplication.run(SpringBootRest2Application.class, args);
}
}

Now we are going to create our beans classes, which we will use for our GET, POST, PUT,
and DELETE REST calls. Create package, com.bhaiti.beans, and add classes into that
package like below:

4. Right-click on the project and select New and then package (New=>Package). Enter the
above package name and click Finish.

5. Now, right-click on the package com.bhaiti.beans and select New->class and provide
the class name, Student, like below:

6/30
package com.bhaiti.kela.beans;

public class Student {

String name;
int age;
String registrationNumber;

public String getName() {


return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getRegistrationNumber() {
return registrationNumber;
}
public void setRegistrationNumber(String registrationNumber) {
this.registrationNumber = registrationNumber;
}
}

6. Now follow steps 5 and create class call StudentRegistration and modify it like below:

package com.bhaiti.kela.beans;

import java.util.ArrayList;
import java.util.List;

public class StudentRegistration {

private List<Student> studentRecords;

private static StudentRegistration stdregd = null;

private StudentRegistration(){
studentRecords = new ArrayList<Student>();
}

public static StudentRegistration getInstance() {

if(stdregd == null) {
stdregd = new StudentRegistration();
return stdregd;
}

9/30
else {
return stdregd;
}
}

public void add(Student std) {


studentRecords.add(std);
}

public String upDateStudent(Student std) {

for(int i=0; i<studentRecords.size(); i++)


{
Student stdn = studentRecords.get(i);
if(stdn.getRegistrationNumber().equals(std.getRegistrationNumber())) {
studentRecords.set(i, std);//update the new record
return "Update successful";
}
}

return "Update un-successful";


}

public String deleteStudent(String registrationNumber) {

for(int i=0; i<studentRecords.size(); i++)


{
Student stdn = studentRecords.get(i);
if(stdn.getRegistrationNumber().equals(registrationNumber)){
studentRecords.remove(i);//update the new record
return "Delete successful";

}}

return "Delete un-successful";


}
public List<Student> getStudentRecords() {
return studentRecords;
}
}

7. Now add a class calls StudentRegistrationReply and modify like below. This class will be
used to reply a response back to the client application

package com.bhaiti.kela.beans;

public class StudentRegistrationReply {

String name;
int age;
String registrationNumber;
String registrationStatus;
10/
30
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getRegistrationNumber() {
return registrationNumber;
}
public void setRegistrationNumber(String registrationNumber) {
this.registrationNumber = registrationNumber;
}
public String getRegistrationStatus() {
return registrationStatus;
}
public void setRegistrationStatus(String registrationStatus) {
this.registrationStatus = registrationStatus;
}

8. Now we will introduce two controllers, one to serve the GET request and the second one
to serve the POST request. With the GET request, we will retrieve all Student Registration
information, and with the POST request, we will add student information into our application.
In spring’s approach to build a RESTful web services, HTTP requests are handled by a
controller. Controller classes/components are easily identified by the @RestController
annotation, and the below StudentRetrieveController will handle GET requests for
/student/allstudent by returning a list of Student class objects in JSON format.

9. Now we will introduce two controllers, one to serve the GET request and the second one
to serve the POST request. With the GET request, we will retrieve all Student Registration
information, and with the POST request, we will add student information into our application.
In spring’s approach to build a RESTful web services, HTTP requests are handled by a
controller. Controller classes/components are easily identified by the @RestController
annotation, and the below StudentRetrieveController will handle GET requests for
/student/allstudent by returning a list of Student class objects in JSON format.

Now just follow step 4 and step 5 and create the package
com.bhaiti.kela.controllers and add the class StudentRetrieveController to it and
import the class Student and modify the class like below:-
11/
30
package com.bhaiti.kela.controllers;

import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bhaiti.kela.beans.Student;
import com.bhaiti.kela.beans.StudentRegistration;

@Controller
public class StudentRetrieveController {

@RequestMapping(method = RequestMethod.GET, value="/student/allstudent")

@ResponseBody
public List<Student> getAllStudents() {
return StudentRegistration.getInstance().getStudentRecords();
}

The @RequestMapping annotation maps all HTTP operations by default and, in this
example, it ensures that HTTP requests to /student/allstudent are mapped to the
getAllStudents() method.

Now we are done with everything for a GET RESTful call. Let’s implement a RESTFul POST
call.

Now it's time to introduce the controller class to handle the POST request. Follow step
5 and add below controller class StudentRegistrationController in
package com.bhaiti.kela.controllers

12/
30
package com.bhaiti.kela.controllers;

import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bhaiti.kela.beans.*;

@Controller
public class StudentRegistrationController {

@RequestMapping(method = RequestMethod.POST, value="/register/student")

@ResponseBody
public StudentRegistrationReply registerStudent(@RequestBody Student student) {
System.out.println("In registerStudent");
StudentRegistrationReply stdregreply = new StudentRegistrationReply();
StudentRegistration.getInstance().add(student);
//We are setting the below value just to reply a message back to the caller
stdregreply.setName(student.getName());
stdregreply.setAge(student.getAge());
stdregreply.setRegistrationNumber(student.getRegistrationNumber());
stdregreply.setRegistrationStatus("Successful");

return stdregreply;
}

Till now, we are done with everything for a GET and POST RESTful call. Let’s test this
application first. After the test, we will learn about PUT and DELETE calls as well. First, we
need to compile the application.

Compilation: To compile this project with Maven, we will add the below information
into the POM file: Double click and open the POM file from project explorer window and
add below information under “<dependencies>” section.

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
13/
30
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

And we'll also add the below information for the property file for this project under the build
section of our POM.xml file (to change the port number at the moment):

<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>

your POM.xml file finally looks like below:

14/
30
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<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>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>

<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>

<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>

14/30
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>

</project>

10. Now open file application.properties under C:\Projects\spring-boot-


rest- 2\src\main\resources and add the below lines in it:

server.port=8083

[email protected]@

11. Now open the command prompt window and go to the project home directory in the
command prompt. In my case, it looks like this:

cd C:\Projects\spring-boot-rest-2

mvnw clean package

If everything goes fine, you can see the below result:

Now run the server:

java -jar target\spring-boot-rest-2-0.0.1-SNAPSHOT.jar

12. Once the server starts successfully, we will test get GET request first. Open your
SOAPUI tool. In SOAPUI tool from file menu select New REST Project and put the below
URL in the address bar and press OK. (File=>New REST Project)

15/30
http://localhost:8083/student/allstudent

13. Now, from the SOAPUI project explorer menu, expand your project and double click on
Request1 and click the green arrow button:

Now you can see the above information. The reason is our student list is empty at the
moment, and to store student information, we need to insert some values in it. For that, we
will use the POST service that we have already implemented.

14. Follow step 10 and insert the below URL in the address box and click OK.

http://localhost:8083/register/student

15. Now you have to select POST this time from Method combo box for a post request.
Once you select POST Media Type, sub pane will emerge from where you have to select
media type to application/json like below and put the below json body in it and click the
green arrow button, which will add the information into our application.

16/30
16. Now go to the GET request project (step 12) and click the green arrow button. You can
see one record like below:

17/30
17. Now go back to POST request test (step 14) and add at least three records and call the
GET request (step 11) and see:

Until now, we have learned how to implement GET and POST services. Now we will learn
PUT and DELETE requests.

18. Now introduce the controller classes to handle PUT and DELETE requests. Follow Step
6 above and add the below two controller classes in it.

Create StudentUpdateController class and modify it like below:

20/24
package com.bhaiti.kela.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bhaiti.kela.beans.Student;
import com.bhaiti.kela.beans.StudentRegistration;

@Controller
public class StudentUpdateController {

@RequestMapping(method = RequestMethod.PUT, value="/update/student")

@ResponseBody
public String updateStudentRecord(@RequestBody Student stdn) {
System.out.println("In updateStudentRecord");
return StudentRegistration.getInstance().upDateStudent(stdn);
}

Create StudentDeleteController and modify it like below:

package com.bhaiti.kela.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.PathVariable;

import com.bhaiti.kela.beans.StudentRegistration;

@Controller
public class StudentDeleteController {

@RequestMapping(method = RequestMethod.DELETE, value="/delete/student/{regdNum}")

@ResponseBody
public String deleteStudentRecord(@PathVariable("regdNum") String regdNum) {
System.out.println("In deleteStudentRecord");
return StudentRegistration.getInstance().deleteStudent(regdNum);
}

21/30
NB: In reality, you don’t need four controller classes to handle four different REST service
calls. One controller class will suffice, but for clarity, I have introduced four different controller
classes in this article.

19. Now stop the server (by using Control-C), and compile the code, and run the server
again.

20. First, insert three to four records into the system by using POST call and retrieve the
records by using GET test mentioned in step 12.

21. Now we will modify a record here, for that create a new REST project in SOAPUI tool
and use the below URL and this time select PUT from method combo box and modify the
records as shown below:

http://localhost:8083/update/student

Once you click green arrow button this information will be updated in the system. Now see
the result, just do the GET call and check.

22/30
22. Now finally we will do the DELETE service call test. Just create a REST project in
SOAPUI and use below URL and select DELETE from method combo box and enter the
record like below and click the green arrow button and to check the final outcome just call the
GET service call.

http://localhost:8083/delete/student/12346 (the last numeric value is registrationNumber)

23/30
24/30
Experiment No. 10
Web Application Example
Aim: Test Frontend web application with Spring Boot.

In this tutorial, we will learn how to build a Spring Boot MVC web application using
SpringMVC and Spring Data JPA.

We will be using the H2 in-memory database for storing the data.

Tools and Technologies Used


- Java 17+

- Spring boot 3+

- Spring framework 6+

- Spring Data JPA

- H2 Database

- Eclipse STS

Development Process
1. Create a Spring Boot Project
2. Create JPA Entity
3. Configure Database
4. Create JPA Repository
5. Create Spring MVC Controller
6. Create a Thymeleaf template
7. Run the Spring boot project
8. Demo

1. Create a Spring Boot Project


Use the below guide to create a Spring boot project in Eclipse STS IDE:
-> Create Spring Boot Project in Spring Tool Suite [STS]

Make sure that you have added below Maven dependencies:

1/8
<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>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>

Create project structure as per the below screenshot:

2/8
2. Create JPA Entity
Let's create a User entity under the domain package and add the following content to it:
import jakarta.persistence.*;

@Entity
@Table(name = "users")
public class User {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;

@Column(name = "name")
private String name;

public User() {
}
public User(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}}

3. Configure Database

Spring boot automatically configures database details for the H2 in-memory database so we
do not need to explicitly add the database configuration in the application.properties file.
Let's add the following properties to the application.properties file:

logging.level.org.springframework=INFO
################### Hibernate Configuration ##########################
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

3/8
SQL Script - Sample Data
Create a data.sql file under /resources folder and add the following content to it:

delete from users;

insert into users(id, name) values(1,'Admin');


insert into users(id, name) values(2,'Ram');
insert into users(id, name) values(3,'Krishna');

1. Create JPA Repository


Let's create a UserRepository for the User entity which gives CRUD database operations
for the User:

import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Integer>


{

2. Create Spring MVC Controller


Let's create UserController to handle HTTP GET requests and return a simple view (
Thymeleaf ):

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 net.sourcecodeexamples.springboot.repositories.UserRepository;

/**
* @author https://www.sourcecodeexamples.net/
* HomeController handles HTTP Get request
*
*/
@Controller
public class HomeController
{
@Autowired UserRepository userRepository;

@GetMapping("/")
public String home(Model model)
{
model.addAttribute("users", userRepository.findAll());
return "index";
4/8
}}

3. Create a Thymeleaf template


Let's create an index.html file under the /resources/templates folder and add the following
content to it:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8"/>
<title>Spring Boot Web App using Spring MVC and Spring Data JPA</title>
</head>
<body>
<h1>Spring Boot Web App using Spring MVC and Spring Data JPA</h1>
<hr />
<table>

<thead>

5/8
<tr>
<th
>Id
</t
</tr>
h>
<th
>Na
me<
/th
>
</thead>
<tbody>
<tr th:each="user : ${users}">
<td th:text="${user.id}">Id</td>
<td th:text="${user.name}">Name</td>
</tr>
</tbody>
</table>
</body>
</html>

4. Run the Spring boot project


This is Spring Boot's main entity class. From your IDE, run the Application.main() method as
a standalone Java class that will start the embedded Tomcat server on port 8080 and point
the browser to http://localhost:8080/.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application
{
public static void main(String[] args)
{
SpringApplication.run(Application.class, args);
}
}

Or use the below command to run the Spring boot app:

$ mvn spring-boot:run

8/8
5. Demo
Hit this URL in a browser: http://localhost:8080/

Conclusion
In conclusion, this tutorial provided a comprehensive guide on building a Spring Boot MVC
web application using Spring MVC and Spring Data JPA. We explored the key concepts and
components of a Spring Boot web application, including controllers, views, and data access
objects. By leveraging Spring MVC, we were able to handle HTTP requests and map them to
appropriate controller methods. Additionally, Spring Data JPA facilitated seamless integration
with the database, enabling efficient data persistence and retrieval. Armed with the
knowledge gained from this tutorial, you are now equipped to embark on your journey of
developing robust and scalable web applications using the Spring Boot framework. So go
ahead and start building amazing web applications with Spring Boot!

9/8

You might also like