Java lab file 2.0
Java lab file 2.0
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. 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.
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:
System.out.println(“Hello World!”);
Output:
Program: 2
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.
• open the command prompt and go to the directory where your file is saved.
Program Code:
class Multvalue
System.out.println(value);
}
Output:
Program: 3
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.
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)
obj.area(20,30);
Output:
Compile-time polymorphism
Program Single-Level Inheritance:
class Employee
{
float salary=40000;
int bonus=10000;
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.
8. Checked Exceptions
9. Unchecked Exceptions
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.
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.
1) It doesn't block the user because threads are independent and you can perform multiple operations at the same
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");
}
}
}
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;
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.
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.*;
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.
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.
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.
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
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.
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;
@Getter @Setter
@Id
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.
}
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.
import org.springframework.web.bind.annotation.GetMapping;
@Controller
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.
Next, let's create an index Thymeleaf template view. Note that we use bootstrap CSS CDN links below the
Thymeleaf HTML page.
<!DOCTYPE html>
>
<head>
<meta charset="UTF-8">
<link
crossorigin="anonymous">
</head>
<body>
<div class="container-fluid">
<span class="navbar-toggler-icon"></span>
</button>
<li class="nav-item">
</li>
</ul>
</div>
</div>
</nav>
<div class="container">
<div class="row">
</div>
</div>
</body>
</html>
package net.javaguides.springboot.service;
import net.javaguides.springboot.dto.UserDto;
import net.javaguides.springboot.entity.User;
import java.util.List;
List<UserDto> findAllUsers();
UserServiceImpl class:-
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 java.util.stream.Collectors;
@Service
@Override
role = checkRoleExist();
user.setRoles(Arrays.asList(role)); userRepository.save(user);
@Override
@Override
.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;
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.
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;
}
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
// 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>
>
<head>
<meta charset="UTF-8">
<link
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 java.util.List;
@Controller
// create model object to store form data UserDto user = new UserDto(); model.addAttribute("user", user);
return "register";
Model model){
!existingUser.getEmail().isEmpty()){
result.rejectValue("email", null,
"There is already an account registered with the same email");
}}
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")
return "users";
package net.javaguides.springboot.controller;
import jakarta.validation.Valid;
import java.util.List;
@Controller
}
<td th:text = "${user.email}"></td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
>
<head>
<meta charset="UTF-8">
<link
integrity="sha384- EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
crossorigin="anonymous">
</head>
<body>
<div class="container-fluid">
<span class="navbar-toggler-icon"></span>
</button>
<li class="nav-item">
</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.
We are implementing database authentication, so let's load the User from the database
CustomUserDetailsService
package com.example.registrationlogindemo.security;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
@Service
@Override
org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(),
mapRolesToAuthorities(user.getRoles()));
}else{
}}
<Role> roles) {
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
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.
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.
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
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 {
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 {
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;
String name;
int age;
String 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;
private StudentRegistration(){
studentRecords = new ArrayList<Student>();
}
if(stdregd == null) {
stdregd = new StudentRegistration();
return stdregd;
}
9/30
else {
return stdregd;
}
}
}}
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;
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 {
@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 {
@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>
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>
server.port=8083
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
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.
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 {
@ResponseBody
public String updateStudentRecord(@RequestBody Student stdn) {
System.out.println("In updateStudentRecord");
return StudentRegistration.getInstance().upDateStudent(stdn);
}
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 {
@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.
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.
- Spring boot 3+
- Spring framework 6+
- 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/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>
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:
import org.springframework.data.jpa.repository.JpaRepository;
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
}}
<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>
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);
}
}
$ 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