[go: up one dir, main page]

0% found this document useful (0 votes)
68 views62 pages

Spring

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 62

Define IOC container and dependency injection in spring ?

IoC Container:
- Definition:
The Inversion of Control (IoC) Container in Spring is the core of the Spring
Framework, responsible for managing the lifecycle of beans (objects). It controls the
instantiation, configuration, and assembly of these beans, thus enabling loose
coupling between components.

- Functionality:
The IoC Container works by using configuration metadata, which could be in the form
of XML, annotations, or Java-based configuration, to understand how the objects
should be instantiated, wired, and managed.

- Types:
Spring provides two main types of IoC containers:
- BeanFactory:
A basic container with lazy initialization of beans.
-ApplicationContext:
A more advanced container that includes additional features such as event
propagation, declarative mechanisms to create a bean, and support for
internationalization.

Dependency Injection:
- Definition:
Dependency Injection (DI) is a design pattern used to implement IoC, where the
control of creating and managing the dependent objects (dependencies) is
transferred from the object itself to the IoC Container.
- Types of DI:
- Constructor Injection:
Dependencies are provided through a class constructor.
- Setter Injection:
Dependencies are provided through setter methods after the object is constructed.
-Field Injection:
(less commonly recommended): Dependencies are injected directly into fields
(attributes).
- Benefits:
DI promotes loose coupling between classes, improves code readability and
testability, and makes it easier to manage and maintain the application. It also allows
for easier switching between different implementations of a dependency.

Example:

public class Car {


private Engine engine;

// Constructor Injection
public Car(Engine engine) {
this.engine = engine;
}
// Setter Injection
public void setEngine(Engine engine) {
this.engine = engine;
}

public void drive() {


engine.start();
System.out.println("Car is driving");
}
}

In this example, the `Car` class depends on the `Engine` class. Instead of creating an
`Engine` object inside the `Car` class, the dependency is injected via the constructor
or setter method by the IoC Container.

This is a typical approach in Spring, where dependencies like `Engine` would be


configured in the Spring IoC Container, and the container would inject them into the
`Car` class as needed.
Explain Advantages of Spring framework ?

The Spring Framework offers several advantages, making it one of the most popular
Java frameworks for enterprise application development. Here are the key benefits:

1. Comprehensive and Modular

● Comprehensive: Spring provides a wide range of modules (Core, AOP, Data


Access, MVC, Security, etc.) that address various aspects of application
development, from configuration management to web applications.
● Modular: You can use only the modules you need, allowing you to keep your
application lightweight and avoid unnecessary overhead.

2. Inversion of Control (IoC) and Dependency Injection (DI)

● IoC: The IoC principle allows developers to delegate the control of object
creation and dependency management to the Spring IoC Container, promoting
loose coupling between components.
● DI: Dependency Injection simplifies code, making it more maintainable,
testable, and modular. It also allows for easy swapping of different
implementations.

3. Aspect-Oriented Programming (AOP)

● Separation of Concerns: AOP in Spring allows you to separate cross-cutting


concerns (like logging, transaction management, and security) from business
logic, resulting in cleaner and more maintainable code.
● Dynamic Proxies: Spring AOP uses dynamic proxies to apply advice (like
before, after, or around advice) to methods, which helps in adding additional
behavior without modifying the core logic.

4. Simplified Data Access

● JDBC Abstraction: Spring provides a JDBC abstraction layer that eliminates


boilerplate code required for database operations. It also handles exceptions
and manages connections, making database interaction more straightforward
and less error-prone.
● Integration with ORM Frameworks: Spring seamlessly integrates with ORM
frameworks like Hibernate, JPA, and MyBatis, simplifying the development of
data access layers.
5. Transaction Management

● Declarative Transaction Management: Spring allows you to manage


transactions declaratively using annotations or XML configurations, reducing
the need to write boilerplate code.
● Consistent Programming Model: Whether you're working with JDBC, JPA, or
JMS, Spring provides a consistent transaction management model that
simplifies coding and enhances application reliability.

6. Support for Unit Testing

● Testability: Spring’s emphasis on DI makes it easy to swap out real


implementations with mock objects, facilitating unit testing.
● Spring Test Framework: Spring provides its own testing framework that
integrates with JUnit or TestNG, making it easier to test components in
isolation and in integration scenarios.

7. Spring MVC for Web Development

● Model-View-Controller Architecture: Spring MVC provides a clear separation


between the model, view, and controller layers, leading to more maintainable
and modular web applications.
● Flexible and Customizable: Spring MVC is highly flexible, allowing you to
customize how requests are handled and how views are rendered. It also
supports RESTful services and web-based applications.

8. Security

● Spring Security: Spring Security is a powerful and customizable authentication


and access control framework. It can secure applications against various
threats, including unauthorized access, session fixation, and CSRF attacks.
● Integration: It integrates well with other Spring modules and can be extended
to meet specific security requirements.

9. Scalability and Performance

● Lightweight: Spring is lightweight and non-intrusive, meaning it doesn’t add


much overhead to the application, ensuring better performance and
scalability.
● Efficient Resource Management: Spring efficiently manages resources such as
database connections, threads, and transactions, contributing to the overall
performance and scalability of the application.
10. Community and Ecosystem

● Large Community: Spring has a large and active community, which means
abundant resources, tutorials, and support are available.
● Extensive Ecosystem: The Spring ecosystem includes projects like Spring Boot,
Spring Cloud, and Spring Batch, which extend the capabilities of the core
framework and simplify the development of complex, distributed systems.

11. Integration with Enterprise Solutions

● Enterprise Java Integration: Spring integrates seamlessly with various


enterprise solutions, including EJB, JMS, and JMX, making it easier to build
enterprise-level applications.
● Integration with Microservices: Spring Boot and Spring Cloud are part of the
Spring ecosystem, providing tools to build and manage microservices-based
architectures efficiently.

12. Flexibility and Portability

● Non-Intrusive: Spring allows you to use only the features you need, without
forcing you to adopt a specific programming model or platform.
● Portability: Spring applications can be easily deployed on various
environments, from standalone servers to cloud platforms, enhancing
portability and reducing vendor lock-in.

These advantages make Spring a preferred choice for developers building scalable,
maintainable, and enterprise-grade Java applications.
Explain Spring Framework with Architecture ?

Spring Framework Architecture



The Spring framework is a widely-used open-source Java framework that provides


a comprehensive programming and configuration model for building enterprise
applications. Its architecture is designed around two core principles: Dependency
Injection (DI) and Aspect-Oriented Programming (AOP).

The Spring framework consists of several modules, which can be categorized into
four main areas: Core Container, Data Access/Integration, Web, and
Miscellaneous. The Core Container provides the fundamental functionality of the
Spring framework, including the IoC container and ApplicationContext. The Data
Access/Integration area provides support for integrating with databases and other
data sources. The Web area provides support for building web applications,
including the Spring MVC and Spring WebFlux modules. The Miscellaneous area
includes other modules that provide additional functionality, such as the Spring
Security module for authentication and authorization features.

● Dependency Injection (DI) is a design pattern that helps to reduce the


coupling between the components of an application. By using DI, the
Spring framework enables loose coupling between components, making
the application more modular and easier to maintain. The Spring
framework provides an Inversion of Control (IoC) container, which is
responsible for creating and managing instances of JavaBeans, and the
ApplicationContext, which provides a unified view of the entire
application configuration.
● Aspect-Oriented Programming (AOP) allows developers to modularize
cross-cutting concerns, such as logging, security, and transaction
management, and apply them to multiple components of an
application. This results in a more modular and reusable codebase. The
Spring framework provides an AOP framework, which is responsible for
managing cross-cutting concerns in the application, such as logging,
security, and transaction management.

● Overall, the Spring framework architecture is based on the principles of


modularity, separation of concerns, and flexibility, providing developers
with a powerful set of tools to build robust, scalable, and maintainable
enterprise applications. The framework’s modular architecture allows
developers to select only the necessary modules for their specific needs,
reducing unnecessary overhead and complexity in the application.
Additionally, the Spring framework’s flexible configuration model allows
developers to configure the application using various approaches, such
as XML-based configuration, Java-based configuration, and
annotation-based configuration.
The Spring framework is modular and consists of several modules that provide
different functionalities to help build enterprise applications.
Core Container
The Core Container provides the fundamental functionality of the Spring framework,
including the Inversion of Control (IoC) container and the ApplicationContext. It
includes the following modules:
Spring Core: This module provides the fundamental functionality of the Spring
framework, including IoC and DI. The IoC container is the heart of the Spring
Framework, responsible for creating and managing instances of JavaBeans. It uses
dependency injection to wire the beans together.
Spring Beans: This module provides the BeanFactory, which is the basic building
block of the IoC container, and the BeanWrapper, which is responsible for managing
the lifecycle of a bean. The Bean Factory is the core interface for accessing the IoC
container. It provides methods for retrieving beans.
Spring Context: This module provides the ApplicationContext, which is an advanced
version of the BeanFactory and provides additional features, such as
internationalization and resource loading, and the ability to publish and consume
events.
Spring Expression Language (SpEL): This module provides a powerful expression
language for querying and manipulating objects during runtime. SpEL supports a
wide range of features, including property access, method invocation, conditionals,
loops, and type conversion. It also provides support for accessing variables and
functions defined in the application context, as well as support for defining custom
functions and variables.
Data Access/Integration
The Data Access/Integration area provides support for integrating with databases and
other data sources. It includes the following modules:
Spring JDBC: This module provides a simple JDBC abstraction layer that reduces the
amount of boilerplate code required to work with JDBC. Spring JDBC provides
support for transaction management, allowing developers to manage database
transactions declaratively using Spring’s transaction management.
Spring ORM: This module provides integration with Object-Relational Mapping
(ORM) frameworks, such as Hibernate and JPA. Spring ORM provides a higher-level
abstraction layer on top of ORM frameworks, allowing developers to write less
boilerplate code and more easily integrate ORM technologies with other Spring
features, such as transaction management and caching.
Spring Data: This module provides a consistent and easy-to-use programming model
for working with data access technologies, including databases, NoSQL, and
cloud-based data services. Spring Data provides a wide range of features, including
automatic CRUD (Create, Read, Update, Delete) operations, query generation from
method names, support for pagination and sorting, integration with Spring’s
transaction management, and more. Additionally, Spring Data provides support for
common data access patterns, such as repositories and data access objects (DAOs).
Spring Transaction: This module provides support for declarative transaction
management in Spring applications. Spring Transaction provides support for various
transaction propagation and isolation levels, allowing developers to manage
transactions at different levels of granularity. Additionally, Spring Transaction
provides support for different transaction management strategies, such as using a JTA
transaction manager or a simple JDBC transaction manager.
Web
The Web area provides support for building web applications. It includes the
following modules:
Spring MVC: This module provides a Model-View-Controller (MVC) framework for
building web applications. Spring MVC provides a range of features, including support
for handling HTTP requests and responses, form handling, data binding, validation,
and more. It also provides support for different view technologies, such as JSP
(JavaServer Pages), Thymeleaf, and Velocity, allowing developers to choose the view
technology that best suits their needs.
Spring WebFlux: This module provides a reactive programming model for building
web applications that require high concurrency and scalability. Spring WebFlux
provides support for building reactive web applications using a range of technologies,
such as Netty, Undertow, and Servlet 3.1+ containers. It also provides a range of
features, including support for reactive data access, reactive stream processing, and
reactive HTTP clients.
Spring Web Services: This module provides support for building SOAP-based and
RESTful web services. Spring Web Services provides support for generating WSDL
(Web Services Description Language) from Java classes, and for generating Java
classes from WSDL. This allows developers to define the contract (i.e., the interface)
of their web service using WSDL, and to generate the Java classes that implement the
web service from the WSDL.
Create HelloWorld Application using Spring ?

Steps to Create a "Hello World" Application Using Spring

1. Set Up a Spring Project

● Option 1: Use Spring Initializr:


○ Visit Spring Initializr.
○ Configure the project with the following options:
■ Project: Maven Project
■ Language: Java
■ Spring Boot Version: Latest stable version (e.g., 3.x.x)
■ Group: com.example
■ Artifact: helloworld
■ Name: HelloWorld
■ Dependencies: Add Spring Web.
○ Click Generate to download the project, unzip it, and open it in your
preferred IDE.
● Option 2: Use an IDE:
○ Create a new Maven project in your IDE (e.g., IntelliJ IDEA, Eclipse).
○ Manually add Spring Boot dependencies to the pom.xml file.

2. Understand the Project Structure

● After setting up, your project directory will have the following structure:

helloworld/

├── src/

│ ├── main/

│ │ ├── java/

│ │ │ └── com/example/helloworld/

│ │ │ ├── HelloWorldApplication.java

│ │ │ └── HelloWorldController.java

│ │ └── resources/

│ │ └── application.properties

└── pom.xml
3.Create the Main Application Class

● In the com.example.helloworld package, create a class named


HelloWorldApplication.java.
● This class serves as the entry point for your Spring Boot application.

package com.example.helloworld;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class HelloWorldApplication {

public static void main(String[] args) {

SpringApplication.run(HelloWorldApplication.class, args);

4.Create a Controller

● In the same package, create another class named


HelloWorldController.java.
● This class will handle HTTP requests and return a simple "Hello, World!"
message.
package com.example.helloworld;

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

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

@RestController

public class HelloWorldController {

@GetMapping("/hello")

public String sayHello() {

return "Hello, World!";

5. Run the Application

● You can run the application using your IDE or the command line.
● Command Line: Navigate to the project directory and execute:

mvn spring-boot:run

6. Access the Application

● Open your web browser and navigate to:


bash
Copy code
http://localhost:8080/hello
Explain annotations in Spring

Annotations in Spring play a crucial role in simplifying configuration and development. They help
eliminate the need for verbose XML configurations by allowing you to define metadata directly in
your code. Here’s an overview of some of the most important annotations in Spring:

1. @SpringBootApplication

● Purpose: Marks the main class of a Spring Boot application and triggers auto-configuration,
component scanning, and allows defining extra configuration on your application class.
● Usage: This annotation combines three key annotations: @Configuration,
@EnableAutoConfiguration, and @ComponentScan.

java

Copy code

@SpringBootApplication

public class MyApplication {

public static void main(String[] args) {

SpringApplication.run(MyApplication.class, args);

2. @Component, @Service, @Repository, @Controller

● Purpose: These annotations are used to define Spring beans and indicate the role of the class
in the application. Spring automatically detects these classes through component scanning
and registers them as beans.

@Component: Generic stereotype for any Spring-managed component.


java
Copy code
@Component

public class MyComponent {

// Bean logic


@Service: Specialization of @Component, used for service layer classes.
java
Copy code
@Service

public class MyService {

// Business logic

@Repository: Specialization of @Component, used for DAO (Data Access Object) classes.
java
Copy code
@Repository

public class MyRepository {

// Database access logic

@Controller: Specialization of @Component, used for defining web controllers.


java
Copy code
@Controller

public class MyController {

// Web handling logic

3. @Autowired

● Purpose: Automatically injects dependencies into Spring-managed beans.


● Usage: Can be used on constructors, methods, or fields.

java

Copy code

@Service

public class MyService {

private final MyRepository myRepository;


@Autowired

public MyService(MyRepository myRepository) {

this.myRepository = myRepository;

4. @Qualifier

● Purpose: Used along with @Autowired to specify which bean to inject when multiple
beans of the same type are available.
● Usage: Provides the name of the specific bean to be injected.

java

Copy code

@Autowired

@Qualifier("specificBeanName")

private MyService myService;

5. @Configuration

● Purpose: Indicates that a class contains @Bean definitions and Spring should process it to
generate Spring beans to be managed by the Spring IoC container.
● Usage: Often used in place of XML configuration files.

java

Copy code

@Configuration

public class AppConfig {

@Bean

public MyService myService() {

return new MyService();

}
6. @Bean

● Purpose: Declares a method as a bean producer, and the returned object is registered as a
Spring bean.
● Usage: Typically used within a class annotated with @Configuration.

java

Copy code

@Bean

public MyService myService() {

return new MyService();

7. @Scope

● Purpose: Defines the scope of a bean (e.g., singleton, prototype).


● Usage: Applied at the class level or on methods annotated with @Bean.

java

Copy code

@Bean

@Scope("prototype")

public MyService myService() {

return new MyService();

8. @Primary

● Purpose: Indicates that a bean should be given preference when multiple beans of the same
type are eligible for autowiring.
● Usage: Applied on a bean definition.

java

Copy code

@Bean
@Primary

public MyService primaryService() {

return new MyServiceImpl();

9. @Value

● Purpose: Injects values into fields, constructor arguments, or method parameters from a
property file or environment variables.
● Usage: Used for injecting configuration values.

java

Copy code

@Value("${my.property}")

private String myProperty;

10. @Controller, @RestController, @RequestMapping

● @Controller: Marks a class as a Spring MVC controller, which can handle web requests.
● @RestController: A combination of @Controller and @ResponseBody, used to create
RESTful web services.
● @RequestMapping: Maps HTTP requests to handler methods in MVC and REST controllers.

java

Copy code

@RestController

@RequestMapping("/api")

public class MyRestController {

@GetMapping("/hello")

public String sayHello() {

return "Hello, World!";

}
11. @RequestParam, @PathVariable, @RequestBody

● @RequestParam: Binds HTTP request parameters to method parameters.


○ Example: If the request URL is http://example.com/api?name=Veera, the
value of the name parameter can be accessed using @RequestParam.

java
Copy code
@GetMapping("/greet")

public String greet(@RequestParam(name = "name", required = false,


defaultValue = "World") String name) {

return "Hello, " + name + "!";


● @PathVariable: Binds URI template variables to method parameters.
○ Example: If the request URL is http://example.com/api/users/1, the
value 1 can be accessed using @PathVariable.

java
Copy code
@GetMapping("/users/{id}")

public String getUser(@PathVariable("id") Long id) {

return "User ID: " + id;


● @RequestBody: Binds the body of an HTTP request to a method parameter. Typically used to
pass JSON or XML data in POST requests.
○ Example: For a POST request with a JSON body, the data can be mapped to a Java
object using @RequestBody.

java
Copy code
@PostMapping("/users")

public User createUser(@RequestBody User user) {

// Logic to save the user

return user;

}
12. @ResponseBody

● Purpose: Indicates that the return value of a method should be used as the response body of
the HTTP response, rather than being interpreted as a view name.
● Usage: Commonly used in RESTful web services to return data directly, such as JSON or XML.

@GetMapping("/data")

@ResponseBody

public String getData() {

return "Some data";

● Note: @RestController is a combination of @Controller and @ResponseBody, so


it’s typically not necessary to use @ResponseBody if you’re using @RestController.

13. @CrossOrigin

● Purpose: Enables cross-origin resource sharing (CORS) for a controller or a specific method.
This is important when your backend and frontend are on different domains or ports.
● Usage: Applied at the class or method level.

@RestController

@CrossOrigin(origins = "http://example.com")

public class MyRestController {

@GetMapping("/data")

public String getData() {

return "Some data";

14. @Transactional

● Purpose: Manages transaction boundaries automatically. When applied to a method, Spring


manages the transaction, rolling back if an exception occurs.
● Usage: Applied on methods or classes that require transaction management.
@Service

public class MyService {

@Transactional

public void performTransaction() {

// Transactional logic

15. @EnableAutoConfiguration

● Purpose: Automatically configures Spring Boot based on the dependencies you have added
to your project. This annotation is typically included in @SpringBootApplication.
● Usage: Enables auto-configuration in a Spring Boot application.

@EnableAutoConfiguration

public class MyApplication {

public static void main(String[] args) {

SpringApplication.run(MyApplication.class, args);

}
Explain Spring Bean Life Cycle Process Flow ?

The lifecycle of any object means when & how it is born, how it behaves
throughout its life, and when & how it dies. Similarly, the bean life cycle
refers to when & how the bean is instantiated, what action it performs
until it lives, and when & how it is destroyed. In this article, we will discuss
the life cycle of the bean.

Bean life cycle is managed by the spring container. When we run the
program then, first of all, the spring container gets started. After that, the
container creates the instance of a bean as per the request, and then
dependencies are injected. And finally, the bean is destroyed when the
spring container is closed. Therefore, if we want to execute some code on
the bean instantiation and just after closing the spring container, then we
can write that code inside the custom init() method and the destroy()
method.

The following image shows the process flow of the bean life cycle.

Note: We can choose a custom method name instead of init() and


destroy(). Here, we will use init() method to execute all its code as the
spring container starts up and the bean is instantiated, and destroy()
method to execute all its code on closing the container.
Ways to implement the life cycle of a bean
Spring provides three ways to implement the life cycle of a bean. In order
to understand these three ways, let’s take an example. In this example, we
will write and activate init() and destroy() method for our bean
(HelloWorld.java) to print some messages on start and close of the Spring
container. Therefore, the three ways to implement this are:

1. By XML: In this approach, in order to avail custom init() and destroy()


methods for a bean we have to register these two methods inside the
Spring XML configuration file while defining a bean. Therefore, the
following steps are followed:

Step 1: Firstly, we need to create a bean HelloWorld.java in this case and


write the init() and destroy() methods in the class.
Step 2: Now, we need to configure the spring XML file spring.xml and
need to register the init() and destroy() methods in it.

Step 3: Finally, we need to create a driver class to run this bean.


Explain Spring JDBC with example.

1. Set Up the Spring Boot Project

● Dependencies: Spring Web, Spring JDBC, MySQL Driver, Thymeleaf (optional


but useful if using JSP).
● Using Spring Initializr:
○ Select the dependencies as mentioned above.

2. Update pom.xml

Add the necessary dependencies for JSP support.

xml

Copy code

<dependencies>

<!-- Other dependencies -->

<!-- JSP -->

<dependency>

<groupId>org.apache.tomcat.embed</groupId>

<artifactId>tomcat-embed-jasper</artifactId>

</dependency>

<dependency>

<groupId>javax.servlet</groupId>

<artifactId>javax.servlet-api</artifactId>

<scope>provided</scope>

</dependency>

<dependency>

<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>

<scope>provided</scope>

</dependency>

<dependency>

<groupId>javax.servlet</groupId>

<artifactId>jstl</artifactId>

</dependency>

</dependencies>

<properties>

<java.version>17</java.version> <!-- Or your preferred version


-->

<spring.mvc.view.suffix>.jsp</spring.mvc.view.suffix>

</properties>

3. Configure the MySQL Database

In src/main/resources/application.properties:

properties

Copy code

# MySQL Configuration

spring.datasource.url=jdbc:mysql://localhost:3306/spring_jdbc

spring.datasource.username=root

spring.datasource.password=yourpassword

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# JDBC

spring.datasource.initialize=true

4. Create the Entity Class

The Student class remains the same as before.

5. Create the DAO Class

This class interacts with the database using JdbcTemplate.

java

Copy code

package com.example.springjdbc.dao;

import com.example.springjdbc.model.Student;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.jdbc.core.JdbcTemplate;

import org.springframework.jdbc.core.RowMapper;

import org.springframework.stereotype.Repository;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.List;

@Repository

public class StudentDAO {

@Autowired
private JdbcTemplate jdbcTemplate;

public int save(Student student) {

String sql = "INSERT INTO students (name, course) VALUES (?,


?)";

return jdbcTemplate.update(sql, student.getName(),


student.getCourse());

public int update(Student student) {

String sql = "UPDATE students SET name = ?, course = ? WHERE


id = ?";

return jdbcTemplate.update(sql, student.getName(),


student.getCourse(), student.getId());

public int delete(int id) {

String sql = "DELETE FROM students WHERE id = ?";

return jdbcTemplate.update(sql, id);

public Student findById(int id) {

String sql = "SELECT * FROM students WHERE id = ?";

return jdbcTemplate.queryForObject(sql, new Object[]{id},


new RowMapper<Student>() {

@Override

public Student mapRow(ResultSet rs, int rowNum) throws


SQLException {
return new Student(rs.getInt("id"),
rs.getString("name"), rs.getString("course"));

});

public List<Student> findAll() {

String sql = "SELECT * FROM students";

return jdbcTemplate.query(sql, new RowMapper<Student>() {

@Override

public Student mapRow(ResultSet rs, int rowNum) throws


SQLException {

return new Student(rs.getInt("id"),


rs.getString("name"), rs.getString("course"));

});

6. Create the Controller

Create a normal Spring MVC controller that handles HTTP requests and returns views (JSP pages).

java

Copy code

package com.example.springjdbc.controller;

import com.example.springjdbc.dao.StudentDAO;

import com.example.springjdbc.model.Student;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

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

import java.util.List;

@Controller

@RequestMapping("/students")

public class StudentController {

@Autowired

private StudentDAO studentDAO;

@GetMapping

public String getAllStudents(Model model) {

List<Student> students = studentDAO.findAll();

model.addAttribute("students", students);

return "students"; // Corresponds to students.jsp

@GetMapping("/{id}")

public String getStudentById(@PathVariable int id, Model model)


{

Student student = studentDAO.findById(id);

model.addAttribute("student", student);
return "student"; // Corresponds to student.jsp

@GetMapping("/new")

public String showCreateForm(Model model) {

model.addAttribute("student", new Student());

return "create-student"; // Corresponds to


create-student.jsp

@PostMapping

public String addStudent(@ModelAttribute("student") Student


student) {

studentDAO.save(student);

return "redirect:/students";

@GetMapping("/edit/{id}")

public String showEditForm(@PathVariable int id, Model model) {

Student student = studentDAO.findById(id);

model.addAttribute("student", student);

return "edit-student"; // Corresponds to edit-student.jsp

@PostMapping("/{id}")

public String updateStudent(@PathVariable int id,


@ModelAttribute("student") Student student) {
student.setId(id);

studentDAO.update(student);

return "redirect:/students";

@GetMapping("/delete/{id}")

public String deleteStudent(@PathVariable int id) {

studentDAO.delete(id);

return "redirect:/students";

7. Create JSP Views

Place these JSP files under src/main/webapp/WEB-INF/jsp/.

students.jsp

jsp

Copy code

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<html>

<head>

<title>Students</title>

</head>

<body>

<h2>Students List</h2>

<table border="1">
<tr>

<th>ID</th>

<th>Name</th>

<th>Course</th>

<th>Actions</th>

</tr>

<c:forEach var="student" items="${students}">

<tr>

<td>${student.id}</td>

<td>${student.name}</td>

<td>${student.course}</td>

<td>

<a href="students/edit/${student.id}">Edit</a>

<a
href="students/delete/${student.id}">Delete</a>

</td>

</tr>

</c:forEach>

</table>

<a href="students/new">Add New Student</a>

</body>

</html>

student.jsp

jsp

Copy code
<html>

<head>

<title>Student Details</title>

</head>

<body>

<h2>Student Details</h2>

<p>ID: ${student.id}</p>

<p>Name: ${student.name}</p>

<p>Course: ${student.course}</p>

<a href="/students">Back to List</a>

</body>

</html>

create-student.jsp

jsp

Copy code

<html>

<head>

<title>Create Student</title>

</head>

<body>

<h2>Create Student</h2>

<form action="/students" method="post">

Name: <input type="text" name="name"><br>

Course: <input type="text" name="course"><br>


<input type="submit" value="Save">

</form>

<a href="/students">Back to List</a>

</body>

</html>

edit-student.jsp

jsp

Copy code

<html>

<head>

<title>Edit Student</title>

</head>

<body>

<h2>Edit Student</h2>

<form action="/students/${student.id}" method="post">

Name: <input type="text" name="name"


value="${student.name}"><br>

Course: <input type="text" name="course"


value="${student.course}"><br>

<input type="submit" value="Update">

</form>

<a href="/students">Back to List</a>

</body>

</html>
8. Create the Database Table

Ensure the students table exists in the spring_jdbc database.

sql

Copy code

CREATE TABLE students (

id INT AUTO_INCREMENT PRIMARY KEY,

name VARCHAR(100),

course VARCHAR(100)

);

9. Run the Application

● Run the SpringJdbcExampleApplication class as a Java application.


● The application will start and listen on http://localhost:8080.

10. Access the Application

● Navigate to http://localhost:8080/students to view the list of students.


● Use the links provided to add, edit, or delete students.

Summary

This example demonstrates how to use Spring JDBC with JSP and a normal Spring MVC controller to
perform CRUD operations with a MySQL database. This approach uses JSP for the view layer and
follows the traditional Model-View-Controller (MVC) pattern in Spring.
Set Up the Spring Boot Project

● Dependencies: Spring Web, Spring JDBC, MySQL Driver, Thymeleaf (optional


but useful if using JSP).
● Using Spring Initializr:
○ Select the dependencies as mentioned above.

2. Update pom.xml

Add the necessary dependencies for JSP support.

xml

Copy code

<dependencies>

<!-- Other dependencies -->

<!-- JSP -->

<dependency>

<groupId>org.apache.tomcat.embed</groupId>

<artifactId>tomcat-embed-jasper</artifactId>

</dependency>

<dependency>

<groupId>javax.servlet</groupId>

<artifactId>javax.servlet-api</artifactId>

<scope>provided</scope>

</dependency>

<dependency>

<groupId>javax.servlet.jsp</groupId>

<artifactId>javax.servlet.jsp-api</artifactId>

<scope>provided</scope>

</dependency>
<dependency>

<groupId>javax.servlet</groupId>

<artifactId>jstl</artifactId>

</dependency>

</dependencies>

<properties>

<java.version>17</java.version> <!-- Or your preferred version


-->

<spring.mvc.view.suffix>.jsp</spring.mvc.view.suffix>

</properties>

3. Configure the MySQL Database

In src/main/resources/application.properties:

properties

Copy code

# MySQL Configuration

spring.datasource.url=jdbc:mysql://localhost:3306/spring_jdbc

spring.datasource.username=root

spring.datasource.password=yourpassword

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# JDBC

spring.datasource.initialize=true

4. Create the Entity Class


The Student class remains the same as before.

5. Create the DAO Class

This class interacts with the database using JdbcTemplate.

java

Copy code

package com.example.springjdbc.dao;

import com.example.springjdbc.model.Student;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.jdbc.core.JdbcTemplate;

import org.springframework.jdbc.core.RowMapper;

import org.springframework.stereotype.Repository;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.List;

@Repository

public class StudentDAO {

@Autowired

private JdbcTemplate jdbcTemplate;

public int save(Student student) {

String sql = "INSERT INTO students (name, course) VALUES (?,


?)";
return jdbcTemplate.update(sql, student.getName(),
student.getCourse());

public int update(Student student) {

String sql = "UPDATE students SET name = ?, course = ? WHERE


id = ?";

return jdbcTemplate.update(sql, student.getName(),


student.getCourse(), student.getId());

public int delete(int id) {

String sql = "DELETE FROM students WHERE id = ?";

return jdbcTemplate.update(sql, id);

public Student findById(int id) {

String sql = "SELECT * FROM students WHERE id = ?";

return jdbcTemplate.queryForObject(sql, new Object[]{id},


new RowMapper<Student>() {

@Override

public Student mapRow(ResultSet rs, int rowNum) throws


SQLException {

return new Student(rs.getInt("id"),


rs.getString("name"), rs.getString("course"));

});

}
public List<Student> findAll() {

String sql = "SELECT * FROM students";

return jdbcTemplate.query(sql, new RowMapper<Student>() {

@Override

public Student mapRow(ResultSet rs, int rowNum) throws


SQLException {

return new Student(rs.getInt("id"),


rs.getString("name"), rs.getString("course"));

});

6. Create the Controller

Create a normal Spring MVC controller that handles HTTP requests and returns views (JSP pages).

java

Copy code

package com.example.springjdbc.controller;

import com.example.springjdbc.dao.StudentDAO;

import com.example.springjdbc.model.Student;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.*;
import java.util.List;

@Controller

@RequestMapping("/students")

public class StudentController {

@Autowired

private StudentDAO studentDAO;

@GetMapping

public String getAllStudents(Model model) {

List<Student> students = studentDAO.findAll();

model.addAttribute("students", students);

return "students"; // Corresponds to students.jsp

@GetMapping("/{id}")

public String getStudentById(@PathVariable int id, Model model)


{

Student student = studentDAO.findById(id);

model.addAttribute("student", student);

return "student"; // Corresponds to student.jsp

@GetMapping("/new")
public String showCreateForm(Model model) {

model.addAttribute("student", new Student());

return "create-student"; // Corresponds to


create-student.jsp

@PostMapping

public String addStudent(@ModelAttribute("student") Student


student) {

studentDAO.save(student);

return "redirect:/students";

@GetMapping("/edit/{id}")

public String showEditForm(@PathVariable int id, Model model) {

Student student = studentDAO.findById(id);

model.addAttribute("student", student);

return "edit-student"; // Corresponds to edit-student.jsp

@PostMapping("/{id}")

public String updateStudent(@PathVariable int id,


@ModelAttribute("student") Student student) {

student.setId(id);

studentDAO.update(student);

return "redirect:/students";

}
@GetMapping("/delete/{id}")

public String deleteStudent(@PathVariable int id) {

studentDAO.delete(id);

return "redirect:/students";

7. Create JSP Views

Place these JSP files under src/main/webapp/WEB-INF/jsp/.

students.jsp

jsp

Copy code

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<html>

<head>

<title>Students</title>

</head>

<body>

<h2>Students List</h2>

<table border="1">

<tr>

<th>ID</th>

<th>Name</th>

<th>Course</th>
<th>Actions</th>

</tr>

<c:forEach var="student" items="${students}">

<tr>

<td>${student.id}</td>

<td>${student.name}</td>

<td>${student.course}</td>

<td>

<a href="students/edit/${student.id}">Edit</a>

<a
href="students/delete/${student.id}">Delete</a>

</td>

</tr>

</c:forEach>

</table>

<a href="students/new">Add New Student</a>

</body>

</html>

student.jsp

jsp

Copy code

<html>

<head>

<title>Student Details</title>

</head>
<body>

<h2>Student Details</h2>

<p>ID: ${student.id}</p>

<p>Name: ${student.name}</p>

<p>Course: ${student.course}</p>

<a href="/students">Back to List</a>

</body>

</html>

create-student.jsp

jsp

Copy code

<html>

<head>

<title>Create Student</title>

</head>

<body>

<h2>Create Student</h2>

<form action="/students" method="post">

Name: <input type="text" name="name"><br>

Course: <input type="text" name="course"><br>

<input type="submit" value="Save">

</form>

<a href="/students">Back to List</a>

</body>
</html>

edit-student.jsp

jsp

Copy code

<html>

<head>

<title>Edit Student</title>

</head>

<body>

<h2>Edit Student</h2>

<form action="/students/${student.id}" method="post">

Name: <input type="text" name="name"


value="${student.name}"><br>

Course: <input type="text" name="course"


value="${student.course}"><br>

<input type="submit" value="Update">

</form>

<a href="/students">Back to List</a>

</body>

</html>

8. Create the Database Table

Ensure the students table exists in the spring_jdbc database.

sql

Copy code
CREATE TABLE students (

id INT AUTO_INCREMENT PRIMARY KEY,

name VARCHAR(100),

course VARCHAR(100)

);

9. Run the Application

● Run the SpringJdbcExampleApplication class as a Java application.


● The application will start and listen on http://localhost:8080.

10. Access the Application

● Navigate to http://localhost:8080/students to view the list of students.


● Use the links provided to add, edit, or delete students.

Summary

This example demonstrates how to use Spring JDBC with JSP and a normal Spring MVC controller to
perform CRUD operations with a MySQL database. This approach uses JSP for the view layer and
follows the traditional Model-View-Controller (MVC) pattern in Spring.

5. Write a program to demonstrate Spring Boot Crud Repository

To demonstrate the use of Spring Boot with CrudRepository, JSP for views, and MySQL for the
database, we'll create a simple application to manage Employee entities. This application will
perform basic CRUD operations: Create, Read, Update, and Delete.

1. Set Up the Spring Boot Project

● Dependencies: Spring Web, Spring Data JPA, MySQL Driver, Thymeleaf


(optional for JSP support).
● Using Spring Initializr:
○ Select:
■ Project: Maven Project
■ Language: Java
■ Spring Boot: Latest stable version (e.g., 3.x.x)
■ Group: com.example
■ Artifact: crud-repo-jsp
■ Dependencies: Spring Web, Spring Data JPA, MySQL Driver, Spring Boot
DevTools

2. Update pom.xml

Add the necessary dependencies for JSP support.

xml

Copy code

<dependencies>

<!-- Other dependencies -->

<!-- Spring Boot Dependencies -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-jpa</artifactId>

</dependency>

<!-- JSP Dependencies -->

<dependency>

<groupId>org.apache.tomcat.embed</groupId>

<artifactId>tomcat-embed-jasper</artifactId>

</dependency>

<dependency>

<groupId>javax.servlet</groupId>

<artifactId>javax.servlet-api</artifactId>

<scope>provided</scope>

</dependency>

<dependency>
<groupId>javax.servlet.jsp</groupId>

<artifactId>javax.servlet.jsp-api</artifactId>

<scope>provided</scope>

</dependency>

<dependency>

<groupId>javax.servlet</groupId>

<artifactId>jstl</artifactId>

</dependency>

</dependencies>

<properties>

<java.version>17</java.version> <!-- Or your preferred version


-->

<spring.mvc.view.prefix>/WEB-INF/jsp/</spring.mvc.view.prefix>

<spring.mvc.view.suffix>.jsp</spring.mvc.view.suffix>

</properties>

3. Configure MySQL Database

In src/main/resources/application.properties, configure the MySQL database


connection.

properties

Copy code

# MySQL Configuration

spring.datasource.url=jdbc:mysql://localhost:3306/crud_example

spring.datasource.username=root

spring.datasource.password=yourpassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# JPA Hibernate

spring.jpa.hibernate.ddl-auto=update

spring.jpa.show-sql=true

spring.jpa.properties.hibernate.format_sql=true

4. Create the Employee Entity

Create an Employee entity representing the table in the database.

java

Copy code

package com.example.crudrepojsp.model;

import jakarta.persistence.Entity;

import jakarta.persistence.GeneratedValue;

import jakarta.persistence.GenerationType;

import jakarta.persistence.Id;

@Entity

public class Employee {

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private Long id;

private String name;


private String department;

private String email;

// Constructors, Getters, Setters, toString

public Employee() {}

public Employee(String name, String department, String email) {

this.name = name;

this.department = department;

this.email = email;

public Long getId() {

return id;

public void setId(Long id) {

this.id = id;

public String getName() {

return name;

}
public void setName(String name) {

this.name = name;

public String getDepartment() {

return department;

public void setDepartment(String department) {

this.department = department;

public String getEmail() {

return email;

public void setEmail(String email) {

this.email = email;

@Override

public String toString() {

return "Employee [id=" + id + ", name=" + name + ",


department=" + department + ", email=" + email + "]";

}
5. Create the EmployeeRepository Interface

Create a repository interface for Employee by extending CrudRepository.

java

Copy code

package com.example.crudrepojsp.repository;

import com.example.crudrepojsp.model.Employee;

import org.springframework.data.repository.CrudRepository;

public interface EmployeeRepository extends CrudRepository<Employee,


Long> {

6. Create the Controller

Create a Spring MVC controller to handle requests and return JSP views.

java

Copy code

package com.example.crudrepojsp.controller;

import com.example.crudrepojsp.model.Employee;

import com.example.crudrepojsp.repository.EmployeeRepository;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.*;
@Controller

@RequestMapping("/employees")

public class EmployeeController {

@Autowired

private EmployeeRepository employeeRepository;

@GetMapping

public String listEmployees(Model model) {

model.addAttribute("employees",
employeeRepository.findAll());

return "employees"; // Corresponds to employees.jsp

@GetMapping("/new")

public String showCreateForm(Model model) {

model.addAttribute("employee", new Employee());

return "create-employee"; // Corresponds to


create-employee.jsp

@PostMapping

public String addEmployee(@ModelAttribute("employee") Employee


employee) {

employeeRepository.save(employee);

return "redirect:/employees";
}

@GetMapping("/edit/{id}")

public String showEditForm(@PathVariable Long id, Model model) {

Employee employee =
employeeRepository.findById(id).orElseThrow(() -> new
IllegalArgumentException("Invalid employee Id:" + id));

model.addAttribute("employee", employee);

return "edit-employee"; // Corresponds to edit-employee.jsp

@PostMapping("/{id}")

public String updateEmployee(@PathVariable Long id,


@ModelAttribute("employee") Employee employee) {

employee.setId(id);

employeeRepository.save(employee);

return "redirect:/employees";

@GetMapping("/delete/{id}")

public String deleteEmployee(@PathVariable Long id) {

Employee employee =
employeeRepository.findById(id).orElseThrow(() -> new
IllegalArgumentException("Invalid employee Id:" + id));

employeeRepository.delete(employee);

return "redirect:/employees";

}
}

7. Create JSP Views

Place these JSP files under src/main/webapp/WEB-INF/jsp/.

employees.jsp

jsp

Copy code

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<html>

<head>

<title>Employees</title>

</head>

<body>

<h2>Employees List</h2>

<table border="1">

<tr>

<th>ID</th>

<th>Name</th>

<th>Department</th>

<th>Email</th>

<th>Actions</th>

</tr>

<c:forEach var="employee" items="${employees}">

<tr>

<td>${employee.id}</td>
<td>${employee.name}</td>

<td>${employee.department}</td>

<td>${employee.email}</td>

<td>

<a href="employees/edit/${employee.id}">Edit</a>

<a
href="employees/delete/${employee.id}">Delete</a>

</td>

</tr>

</c:forEach>

</table>

<a href="employees/new">Add New Employee</a>

</body>

</html>

create-employee.jsp

jsp

Copy code

<html>

<head>

<title>Create Employee</title>

</head>

<body>

<h2>Create Employee</h2>

<form action="/employees" method="post">

Name: <input type="text" name="name"><br>


Department: <input type="text" name="department"><br>

Email: <input type="text" name="email"><br>

<input type="submit" value="Save">

</form>

<a href="/employees">Back to List</a>

</body>

</html>

edit-employee.jsp

jsp

Copy code

<html>

<head>

<title>Edit Employee</title>

</head>

<body>

<h2>Edit Employee</h2>

<form action="/employees/${employee.id}" method="post">

Name: <input type="text" name="name"


value="${employee.name}"><br>

Department: <input type="text" name="department"


value="${employee.department}"><br>

Email: <input type="text" name="email"


value="${employee.email}"><br>

<input type="submit" value="Update">

</form>

<a href="/employees">Back to List</a>


</body>

</html>

8. Create the Database Table

Ensure the employee table exists in the crud_example database.

sql

Copy code

CREATE DATABASE crud_example;

USE crud_example;

CREATE TABLE employee (

id BIGINT PRIMARY KEY AUTO_INCREMENT,

name VARCHAR(100),

department VARCHAR(100),

email VARCHAR(100)

);

9. Run the Application

● Run the CrudRepoJspApplication class as a Java application.


● The application will start and listen on `http://localhost:8080

You might also like