08_Prajwal Dikshit_AdvJava_Rubrics
08_Prajwal Dikshit_AdvJava_Rubrics
Practical No:01
a) Aim: write a java program to demonstrate a Generic class.
Theory: Generic Class (Box<T>):
• This is a class that can work with any data type (like Integer, String,
Double, etc.)
using the type parameter T. You specify the actual type when creating an
object.
• T is a placeholder that will be replaced by an actual type when the class
is
instantiated.
• Generic Methods:
• getValue(): Returns the value of the generic type T.
• setValue(): Sets the value of the generic type T.
• displayType(): Prints the actual type of the value stored in the Box
instance using
value.getClass().getName().
• Main Method (GenericDemo):
• We create instances of Box with different types (Integer, String,
Double).
• For each instance, we display the type and value, demonstrating how the
same
class can work with multiple types without requiring separate
implementations for
each.
Output:
}
if (z.compareTo(max) > 0) {
max = z; // z is the maximum so far
}
return max; // Return the maximum value
}
System.out.println("Integer array:");
printArray(intArray); // Prints the elements of intArray
System.out.println("String array:");
printArray(stringArray); // Prints the elements of stringArray
System.out.println("Double array:");
printArray(doubleArray); // Prints the elements of doubleArray
Output:
// List of Doubles
List<Double> doubleList = new ArrayList<>();
doubleList.add(1.1);
doubleList.add(2.2);
doubleList.add(3.3);
// List of Strings
List<String> stringList = new ArrayList<>();
stringList.add("Apple");
stringList.add("Banana");
stringList.add("Cherry");
Output:
Practical No:02
Aim: Write a Java program to create List containing list of items of type String
and use for- - each loop to print the items of the list.
Theory: Using List and For-Each Loop in Java
Introduction to List: In Java, a List is an ordered collection (also known
as a sequence). It allows duplicate elements and maintains the order in
which elements are inserted. The ArrayList class is a resizable array that
implements the List interface.
Creating a List: To create a list of items of type String, we use the
Arraylist class. This class is part of the java.util package, which provides
collections framework classes.
Adding Items to the List: Items can be added to the list using the add me
thod. This method appends the specified element to the end of the list.
Using For-Each Loop: The for-
each loop, also known as the enhanced for loop, is used to iterate over ele
ments of a collection. This loop simplifies the code by eliminating the nee
d for explicit iterator handling.
Printing the Items: By using the for-
each loop, we can easily traverse the list and print each item. The loop aut
omatically handles the indexing and iteration.
Source Code: import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
// Creating a list of Strings
List<String> items = new ArrayList<>();
// Adding items to the list
items.add("Apple");
items.add("Banana");
items.add("Mango");
items.add("Orange");
Output:
b)Aim: Write a Java program to create List containing list of items and use
ListIterator interface to print items present in the list. Also print the list in
reverse/ backword direction.
SourceCode: import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
public class Main {
public static void main(String[] args) {
// Creating a list of Strings
List<String> items = new ArrayList<>();
// Adding items to the list
items.add("Apple");
items.add("Banana");
items.add("Mango");
items.add("Orange");
// Creating a ListIterator to iterate over the list
ListIterator<String> listIterator = items.listIterator();
// Printing the list in forward direction
System.out.println("List in forward direction:");
while (listIterator.hasNext()) {
System.out.println(listIterator.next());
}
// Printing the list in reverse (backward) direction
System.out.println("\nList in reverse direction:");
while (listIterator.hasPrevious()) {
System.out.println(listIterator.previous());
}
}
Output:
Output:
b)Aim: Write a Java program using Set interface containing list of items and
perform the
following operations:
a. Add items in the set.
b. Insert items of one set in to other set.
c. Remove items from the set.
d. Search the specified item in the set.
SourceCode: import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main(String[] args) {
// Creating a Set of Strings
Set<String> set1 = new HashSet<>();
// a. Add items to the set
set1.add("Apple");
set1.add("Banana");
set1.add("Mango");
set1.add("Orange");
System.out.println("Set 1 after adding items: " + set1);
// Creating another Set of Strings
Set<String> set2 = new HashSet<>();
set2.add("Grapes");
set2.add("Pineapple");
// b. Insert items of set2 into set1 (Union)
set1.addAll(set2);
Output:
}
}
Output:
Practical No:05
Assignments on Lambda Expression
a) Aim: Write a Java program using Lambda Expression to print ”Hello
World”.
Theory: Functional Interface (HelloWorld):
o We define a functional interface HelloWorld with a single abstract method
printMessage(). A functional interface is required for using lambda
expressions in Java (an interface with exactly one abstract method).
o The @FunctionalInterface annotation is optional but helps to ensure that
the interface contains exactly one abstract method.
• Lambda Expression:
o The lambda expression () -> System.out.println("Hello World")
provides the implementation for the printMessage() method of the
HelloWorld interface. The lambda expression essentially says "when
printMessage() is called, execute the code to print Hello World".
o This simplifies the need to create an anonymous class or separate
implementation for the interface.
• Main Method:
o In the main() method, the lambda expression is assigned to a variable
hello, which is of type HelloWorld.
o When hello.printMessage() is called, the lambda expression is
executed, and "Hello World" is printed.
Source Code: @FunctionalInterface
interface HelloWorld {
void printMessage();
}
public class LambdaHelloWorld {
public static void main(String[] args) {
// Lambda expression to implement the HelloWorld interface
HelloWorld hello = () -> System.out.println("Hello World");
// Calling the method to print the message
hello.printMessage();
}
}
Output:
SourceCode: @FunctionalInterface
interface Greeting {
void sayHello(String name);
}
}
}
Output:
SourceCode: @FunctionalInterface
interface AddNumbers {
int add(int a, int b);
}
// Calling the method to add two numbers and print the result
System.out.println("Sum of 10 and 20: " + add.add(10, 20));
System.out.println("Sum of 50 and 30: " + add.add(50, 30));
}
}
Output:
Output:
Output:
// Another example
Output:
Practical No:06
Assignments based on web application development using JSP
Theory:
JavaServer Pages (JSP) is a technology used to create dynamic web content. JSP is built on top
of the Java Servlets API and is used to serve dynamically generated web pages based on
HTML, XML, or other document types.
Advantages of JSP
1. Simplified Development: JSP allows for embedding Java code directly into HTML,
which simplifies the development process.
2. Separation of Concerns: By using JSP, developers can separate the presentation logic
(the HTML) from the business logic (the Java code), leading to cleaner and more
maintainable code.
3. Reusability: JSP supports the reuse of components such as JavaBeans and custom tags,
which can improve code reuse and reduce redundancy.
4. Performance: Since JSP pages are compiled into servlets, they offer high performance
and scalability.
JSP Lifecycle
1. Translation: The JSP file is converted into a servlet by the JSP engine.
2. Compilation: The servlet is compiled into a Java class.
3. Class Loading: The compiled class is loaded into the server’s memory.
4. Instantiation: An instance of the servlet is created.
5. Initialization: The jspInit() method is called to initialize the servlet.
6. Request Processing: The service() method is called to handle client requests. For JSP,
this method is _jspService().
7. Destroy: The jspDestroy() method is called when the servlet is taken out of service.
Directives: These are messages that tell the JSP engine how to handle the JSP page.
Examples include <%@ page %>, <%@ include %>, and <%@ taglib %>.
Scriptlets: Code snippets embedded within JSP pages, enclosed in <% %>. They allow
Java code to be inserted into the HTML.
Expressions: Short snippets that output values to the client, enclosed in <%= %>.
Declarations: Used to declare variables and methods, enclosed in <%! %>.
Action Tags: Standard JSP actions like <jsp:include>, <jsp:forward>, and <jsp:useBean>.
JSP Directives
Page Directive: Defines attributes for the entire JSP page. Example: <%@ page
contentType="text/html" language="java" %>.
Include Directive: Includes a file during the translation phase. Example: <%@ include
file="header.jsp" %>.
Taglib Directive: Declares a tag library containing custom tags. Example: <%@ taglib
prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>.
Scriptlets: Used to embed Java code in JSP. Example: <% int i = 0; %>.
Expressions: Outputs Java expressions to the client. Example: <%= new Date() %>.
Declarations: Declares variables and methods. Example: <%! int counter = 0; %>.
JSP Actions
1. Create JSP Files: Write your JSP code and save it with a .jsp extension.
2. Deploy to Server: Place the JSP files in the web application directory (e.g., webapps
directory in Tomcat).
3. Access the Application: Navigate to the JSP page URL in your browser (e.g.,
http://localhost:8080/yourapp/index.jsp).
Aim: Create a Telephone directory using JSP and store all the information
within a database, so that later could be retrieved as per the requirement.
Make your own assumptions
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnection {
private static Connection connection;
// Database credentials
private static final String DB_URL =
"jdbc:mysql://localhost:3306/telephone_directory";
private static final String USER = "root"; // Change to your MySQL
username
private static final String PASSWORD = "password"; // Change to
your MySQL password
public static Connection getConnection() {
if (connection == null) {
try {
// Establish the connection
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection(DB_URL, USER,
PASSWORD);
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
}
return connection;
}
}
Step 4: Create the JSP Files
We need at least two JSP files:
1. index.jsp - The main page for displaying the contacts.
2. addcontact.jsp - A form to add new contacts.
3. Create index.jsp (in src/main/webapp):
jsp
Copy code
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%@ page import="com.telephonedirectory.DBConnection" %>
<html>
<head>
<title>Telephone Directory</title>
</head>
<body>
<h2>Telephone Directory</h2>
<form action="addcontact.jsp">
<input type="submit" value="Add Contact">
</form>
<h3>Contact List:</h3>
<table border="1">
<tr>
<th>Name</th>
<th>Phone</th>
<th>Email</th>
</tr>
<%
Connection conn = DBConnection.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM contacts");
while (rs.next()) {
String name = rs.getString("name");
String phone = rs.getString("phone");
String email = rs.getString("email");
%>
<tr>
<td><%= name %></td>
<td><%= phone %></td>
<td><%= email %></td>
</tr>
<%
}
rs.close();
stmt.close();
conn.close();
%>
</table>
</body>
</html>
4. Create addcontact.jsp (in src/main/webapp): This page contains a form
for adding new contacts to the directory.
jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="com.telephonedirectory.DBConnection" %>
<%@ page import="java.sql.*" %>
<html>
<head>
<title>Add New Contact</title>
</head>
<body>
<h2>Add New Contact</h2>
ps.executeUpdate();
ps.close();
conn.close();
// Redirect to index.jsp to view the updated contact list
response.sendRedirect("index.jsp");
}
%>
</body>
</html>
Step 6: Deploy and Test
1. Run the Project:
o Right-click on the project > Run As > Run on Server.
o Select your Tomcat server and run.
2. Add Contacts:
o Go to the index.jsp page in the browser. You should see a list of
contacts (if any are already added).
o Click Add Contact, and the form will allow you to enter a new
contact.
o After submitting the form, the data will be inserted into the
database, and you will be redirected back to index.jsp to view the
updated list.
Output:
Practical 6.2
Aim: Write a JSP page to display the Registration form (Make your own assumptions)
Code:
Index.jsp
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Registration Form</title>
<style>
*{
margin: 0;
padding: 0;
box-sizing: border-box;
html, body {
width: 100%;
height: 100%;
.contact {
.contact h2 {
text-align: center;
margin-bottom: 40px;
font-size: 2rem;
.contact-form {
max-width: 600px;
margin: 0 auto;
background: #ffffff;
padding: 20px;
border-radius: 8px;
.contact-form label {
display: block;
margin-bottom: 8px;
font-size: 1rem;
width: 100%;
padding: 10px;
margin-bottom: 15px;
border-radius: 4px;
.contact-form button {
background-color: #f5a623;
color: #fff;
border: none;
border-radius: 5px;
font-size: 1rem;
cursor: pointer;
.contact-form button:hover {
background-color: #e59423;
.contact-info {
margin-top: 20px;
text-align: center;
.contact-info p {
font-size: 1rem;
margin: 5px 0;
.map {
height: 300px;
margin-top: 20px;
</style>
</head>
<body>
<div class="container">
<h2>Registration Form</h2>
</form>
</div>
</section>
</body>
</html>
Displayinfo.jsp
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<%
%>
<h2>User Details:</h2>
<p>
<strong>Name:</strong>
<%=uname%></p>
<p>
<strong>Email:</strong>
<%=email%></p>
<p>
<strong>Password:</strong>
<%=password%></p>
<p>
<strong>Gender:</strong>
<%=phone%></p>
</body>
</html>
Output:
Practical 6.3
Aim: Write a JSP program to add, delete and display the records from StudentMaster (RollNo,
Name, Semester, Course) table
Code:
Index.jsp
<html>
<head>
<title>Student Management</title>
</head>
<body>
</form>
</form>
<h2>Student Records</h2>
<%
%>
<table border="1">
<tr>
<th>Roll No</th>
<th>Name</th>
<th>Semester</th>
<th>Course</th>
</tr>
<%
while (rs.next()) {
%>
<tr>
</tr>
<%
%>
</table>
</body>
</html>
addStudent.jsp
<html>
<body>
<%
String query = "INSERT INTO StudentMaster (RollNo, Name, Semester, Course) VALUES (?, ?, ?, ?)";
pstmt.setInt(1, rollno);
pstmt.setString(2, name);
pstmt.setInt(3, semester);
pstmt.setString(4, course);
if (result > 0) {
} else {
%>
</body>
</html>
deleteStudent.jsp
<html>
<body>
<%
pstmt.setInt(1, rollno);
if (result > 0) {
} else {
%>
</body>
</html>
dbconnect.jsp
<%
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
e.printStackTrace();
%>
Output:
Practical 6.4
Aim: Design Loan calculator using JSP which accepts Period of Time (in years) and Principal Loan
Amount. Display the payment amount for each loan and then list the loan balance and interest
paid for each payment over the term of the loan for the following time period and
interest rate:
a) 1 to 7 year at 5.35%
b) 8 to 15 year at 5.5%
c) 16 to 30 year at 5.75%
Code:
index.jsp
pageEncoding="UTF-8"%>
<html>
<head>
<title>Loan Calculator</title>
</head>
<body>
<h2>Loan Calculator</h2>
</form>
</body>
</html>
loanCalculator.jsp
<html>
<head>
</head>
<body>
<%
double annualInterestRate;
annualInterestRate = 5.35;
annualInterestRate = 5.5;
annualInterestRate = 5.75;
} else {
return;
out.println("<h3>Loan Summary</h3>");
double totalInterestPaid = 0;
out.println("<h3>Payment Schedule</h3>");
out.println("<table border='1'>");
out.println(
balance -= principalPaid;
totalInterestPaid += interestPaid;
if (balance < 0) {
balance = 0;
out.println("</table>");
%>
<br>
<br>
</body>
</html>
Output:
Practical 6.5
Aim: Write a program using JSP that displays a webpage consisting an Application form for change
of Study Center which can be filled by any student who wants to change his/ her study center.
Make necessary assumptions.
Code:
index.jsp
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
body {
background-color: #f4f4f9;
padding: 20px;
.container {
width: 50%;
margin: 0 auto;
background-color: #ffffff;
padding: 20px;
border-radius: 8px;
h2 {
text-align: center;
label {
font-weight: bold;
width: 100%;
padding: 8px;
margin: 10px 0;
border-radius: 4px;
input[type="submit"] {
background-color: #4CAF50;
color: white;
border: none;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
border-radius: 4px;
input[type="submit"]:hover {
background-color: #45a049;
.error {
color: red;
font-size: 0.9em;
</style>
</head>
<body>
<div class="container">
</form>
</div>
</body>
</html>
ProcessForm.jsp
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<div class="container">
<div class="details">
<p>
<strong>Student ID:</strong>
<%=request.getParameter("studentId")%></p>
<p>
<strong>Name:</strong>
<%=request.getParameter("name")%></p>
<p>
<%=request.getParameter("currentCenter")%></p>
<p>
<%=request.getParameter("newCenter")%></p>
<p>
<%=request.getParameter("reason")%></p>
</div>
</div>
</body>
</html>
Output:
Practical 6.6
Aim: Write a JSP program that demonstrates the use of JSP declaration, scriptlet, directives,
expression, header and footer
Code:
Jsp_demo.jsp
<html>
<head>
<title>JSP Demo</title>
</head>
<body>
}%>
<p>
<%=getWelcomeMessage()%></p>
<%
%>
<p>
JSP Expression:
<br />
<br />
<%
%>
<br />
<br />
</body>
</html>
Header.jsp
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<header>
</header>
</body>
</html>
Footer.jsp
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<body>
<footer>
</footer>
</body>
</html>
Output:
Theory:
The Spring Framework provides a comprehensive programming and configuration model for
modern Java-based enterprise applications - on any kind of deployment platform.
A key element of spring is infrastructural support at the application level: Spring focuses on
the "plumbing" of enterprise applications so that teams can focus on application-level
business logic, without unnecessary ties to specific deployment environments.
Spring Framework is built on top of two design concepts Dependency Injection and Aspect
Oriented Programming.
7.1. Aim: Write a program to print “Hello World” using spring framework.
Code:
Pom.xml
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>6.1.14</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.1.14</version>
</dependency>
</dependencies>
Config.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
</bean>
</beans>
HelloWorld.java
package com.helloWorld;
return txt;
this.txt = txt;
Main.java
package com.helloWorld;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
System.out.println(txt.getTxt());
Output:
Practical 7.2
Aim: Write a program to demonstrate dependency injection via Setter injection method.
Theory:
Setter injection is a dependency injection in which the spring framework injects the
dependency object using the setter method.
The call first goes to no argument constructor and then to the setter method. It does not
create any new bean instance.
This is the simpler of the two DI methods. In this, the DI will be injected with the help of
setter and/or getter methods.
To set the DI as SDI in the bean, it is done through the beanconfiguration file for this, the
property to be set with the SDI is declared under the <property> tag in the bean-config file.
Code:
Pom.xml
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>6.1.14</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.1.14</version>
</dependency>
</dependencies>
Config.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
</bean>
</bean>
</beans>
Main.java
package com.spring.dependency;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
ClassPathXmlApplicationContext("com/spring/dependency/config.xml");
System.out.println(s);
Student.java
package com.spring.dependency;
return teacher;
this.teacher = teacher;
return rollNumber;
this.rollNumber = rollNumber;
return name;
this.name = name;
@Override
return "Student [rollNumber=" + rollNumber + ", name=" + name + ", teacher=" + teacher + "]";
Teacher.java
package com.spring.dependency;
return name;
this.name = name;
return courseName;
this.courseName = courseName;
@Override
Output:
Practical 7.3
Aim: Write a program to demonstrate dependency injection via Constructor injection method.
Theory:
The constructor injection is the method of injecting the dependencies of an object through
its constructor arguments.
Since constructor invokes at the time of object instantiation, dependencies are pushed into
the object through the constructor arguments at the time of instantiating it.
We can inject the dependency by constructor by using the <constructorarg> sub element of
<bean> in spring configuration file.
Code:
Pom.xml
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>6.1.14</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.1.14</version>
</dependency>
</dependencies>
Config.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
</bean>
</bean>
</beans>
Main.java
package com.example.constructor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
System.out.println(s);
Student.java
package com.example.constructor;
super();
this.rollNumber = rollNumber;
this.name = name;
this.teacher = teacher;
@Override
return "Student [rollNumber=" + rollNumber + ", name=" + name + ", teacher=" + teacher + "]";
Teacher.java
package com.example.constructor;
super();
this.name = name;
this.courseName = courseName;
@Override
Output:
Practical 7.4
Code:
Pom.xml
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>6.1.14</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.1.14</version>
</dependency>
<dependency>
<groupId>com.example</groupId>
<artifactId>HelloWorldSpring</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
package com.annotations;
AppConfig.java
package com.annotations;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "com.annotations")
EmailService.java
package com.annotations;
import org.springframework.stereotype.Service;
@Service
@Override
NotificationController.java
package com.annotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
this.messageService = messageService;
return messageService;
@Autowired
this.messageService = messageService;
messageService.sendMessage(message);
Main.java
package com.annotations;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
controller.notifyUser("Bruce");
Output:
Theory:
@Before is an advice type which ensures that an advice runs before the method execution.
The @Before annotation takes a pointcut expression as a parameter, which specifies the join
points where the advice should be applied. A pointcut expression is a way of selecting join
points based on various criteria, such as the name, the arguments, the annotations, or the
type of the target method.
Code:
File Structure
LoggingAspect.java
package com.springAopPract.beforeAdvice;
import org.aspectj.lang.annotation.Before;
// Before Advice
@Before("execution(* com.example.service.SimpleService.performTask(..))")
Main.java
package com.springAopPract.beforeAdvice;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
System.out.println("Calling performTask()");
simpleService.performTask();
} }
SimpleService.java
package com.springAopPract.beforeAdvice;
Spring-onfig.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<aop:aspectj-autoproxy/>
</beans>
Output:
Practical 8.2
Theory:
After advice is a type of advice in Spring AOP that is executed after a join point, regardless of
the outcome of the target method. It can be used to perform some clean-up tasks, such as
releasing resources, closing connections, logging results, etc.
To define an after advice, you need to use the @After annotation on a method in an aspect
class. The @After annotation takes a pointcut expression as a parameter, which specifies the
join points where the advice should be applied.
Code:
FileStructure:
LoggingAspect.java
package com.afterAdvice;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
@Aspect
@After("execution(* com.afterAdvice.SimpleService.performTask(..))")
Main.java
package com.afterAdvice;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
System.out.println("Calling performTask()");
simpleService.performTask();
SimpleService.java
package com.afterAdvice;
spring-config.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<aop:aspectj-autoproxy/>
</beans>
Output:
Practical 8.3
Theory:
Around advice is a type of advice in Spring AOP that is executed around a join point, which
means it can run both before and after the target method. It can also modify the arguments,
the return value, or the exception of the target method, or even prevent the target method
from executing at all. It is the most powerful and flexible type of advice in Spring AOP.
To define an around advice, you need to use the @Around annotation on a method in an
aspect class. The @Around annotation takes a pointcut expression as a parameter, which
specifies the join points where the advice should be applied.
throws Throwable {
Code :
FileStructure:
LoggingAspect.java
package com.aroundAdvice;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
@Aspect
// Around Advice
@Around("execution(* com.aroundAdvice.SimpleService.performTask(..))")
return result;
Main.java
package com.aroundAdvice;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
System.out.println("Calling performTask()");
simpleService.performTask();
SimpleService.java
package com.aroundAdvice;
Spring-config.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<aop:aspectj-autoproxy/>
</beans>
Output:
Practical 8.4
Theory:
After returning advice is a type of advice in Spring AOP that is executed after a join point
method returns normally, without throwing any exception. It can be used to perform some
post-processing tasks, such as logging the return value, updating the cache, sending
notifications, etc.
After returning advice is a type of advice in Spring AOP that is executed after a join point
method returns normally, without throwing any exception. It can be used to perform some
post-processing tasks, such as logging the return value, updating the cache, sending
notifications, etc.
joinPoint.getSignature(), result);
}}
Code:
File Structure:
LoggingAspect.java
package com.afterReturningAdvice;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
@Aspect
Main.java
package com.afterReturningAdvice;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
System.out.println("Calling getResult()");
SimpleService.java
package com.afterReturningAdvice;
Spring-config.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<aop:aspectj-autoproxy/>
</beans>
Pom.xml
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.10</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.3.10</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.9.1</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.9.1</version>
</dependency>
</dependencies>
Output:
Practical 8.5
Theory:
After throwing advice is a type of advice in Spring AOP that is executed when a join point
method throws an exception. It can be used to handle the exception, log the error, or
perform some recovery actions.
To define an after throwing advice, you need to use the @AfterThrowing annotation on a
method in an aspect class.
public void logException(JoinPoint joinPoint, Exception ex) { log.error("An exception occurred while
reading file: {}", joinPoint.getSignature(), ex);
sendEmail(ex.getMessage());}}
Code:
File Structure
LoggingAspect.java
package com.afterAdvice;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
@Aspect
@After("execution(* com.afterAdvice.SimpleService.performTask(..))")
Main.java
package com.afterAdvice;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
System.out.println("Calling performTask()");
simpleService.performTask();
SimpleService.java
package com.afterAdvice;
Config.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<aop:aspectj-autoproxy/>
</beans>
Output:
Practical 8.6
Theory:
Pointcut advice is a term that refers to the combination of a pointcut and an advice in Spring
AOP. A pointcut is a predicate that matches the join points where the advice should be
applied, and an advice is an action that is executed at those join points. Pointcut advice is a
way of defining the cross-cutting concerns that are modularized by aspects.
Code :
File Structure
Pom.xml
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.3.23</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.5.4</version> <!-- Use the version you are working with -->
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.23</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.3.23</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.32</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>lookback-classic</artifactId>
<version>1.2.6</version>
</dependency>
</dependencies>
AppConfig.java
package com.example;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration
CustomAnnotation.java
package com.example;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
MyPointcutAspect.java
package com.example;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Aspect
@Component
@Pointcut("execution(* com.example.MyService.*(..))")
@Pointcut("execution(* com.example.MyService.methodWithArgs(int))")
@Pointcut("execution(String com.example.MyService.processMessage(..))")
@Pointcut("@annotation(com.example.CustomAnnotation)")
@Before("allMethodsInMyService()")
@Before("methodWithIntArgument()")
@Before("methodReturningString()")
@Before("methodsWithCustomAnnotation()")
MyService.java
package com.example;
import org.springframework.stereotype.Component;
import com.example.CustomAnnotation;
@Component
MainApp.java
package com.example;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
myService.greeting("Alice");
myService.farewell("Bob");
myService.methodWithArgs(25);
// Test method with annotation (you need to create the annotation first)
myService.methodWithAnnotations();
Output:
9.1. Aim: Write a program to demonstrate ADD, UPDATE AND DELETE i.e CRUD OPERATIONS in
Spring JDBC.
Theory:
While working with the database using plain old JDBC, it becomes cumbersome to write
unnecessary code to handle exceptions, opening and closing database connections, etc.
However, Spring JDBC Framework takes care of all the lowlevel details starting from opening
the connection, prepare and execute the SQL statement, process exceptions, handle
transactions and finally close the connection.
So what you have to do is just define the connection parameters and specify the SQL
statement to be executed and do the required work for each iteration while fetching data
from the database.
Spring JDBC provides several approaches and correspondingly different classes to interface
with the database.
I'm going to take classic and the most popular approach which makes use of JdbcTemplate
class of the framework.
This is the central framework class that manages all the database communication and
exception handling.
Spring JDBC provides several approaches and correspondingly different classes to interface
with the database. I'm going to take classic and the most popular approach which makes use
of JdbcTemplate class of the framework.
Code:
File Structure
name VARCHAR(100),
role VARCHAR(100) );
Pom.xml
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.3.10</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.10</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.10</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>2.0.16</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.5.12</version>
<scope>test</scope>
</dependency>
</dependencies>
EmployeeDAO.java
package com.journaldev.spring.jdbc.dao;
import java.util.List;
import com.journaldev.spring.jdbc.model.Employee;
//CRUD operations
//Create
//Read
//Update
//Delete
//Get All
EmployeeDAOImpl.java
package com.journaldev.spring.jdbc.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import com.journaldev.spring.jdbc.model.Employee;
this.dataSource = dataSource;
@Override
String query = "insert into Employee (id, name, role) values (?,?,?)";
PreparedStatement ps = null;
try {
con = dataSource.getConnection();
ps = con.prepareStatement(query);
ps.setInt(1, employee.getId());
ps.setString(2, employee.getName());
ps.setString(3, employee.getRole());
if (out != 0) {
} else
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
ps.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
@Override
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = dataSource.getConnection();
ps = con.prepareStatement(query);
ps.setInt(1, id);
rs = ps.executeQuery();
if (rs.next()) {
emp.setId(id);
emp.setName(rs.getString("name"));
emp.setRole(rs.getString("role"));
} else {
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
rs.close();
ps.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
return emp;
@Override
PreparedStatement ps = null;
try {
con = dataSource.getConnection();
ps = con.prepareStatement(query);
ps.setString(1, employee.getName());
ps.setString(2, employee.getRole());
ps.setInt(3, employee.getId());
if (out != 0) {
} else
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
ps.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
@Override
PreparedStatement ps = null;
try {
con = dataSource.getConnection();
ps = con.prepareStatement(query);
ps.setInt(1, id);
if (out != 0) {
} else
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
ps.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
@Override
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = dataSource.getConnection();
ps = con.prepareStatement(query);
rs = ps.executeQuery();
while (rs.next()) {
emp.setId(rs.getInt("id"));
emp.setName(rs.getString("name"));
emp.setRole(rs.getString("role"));
empList.add(emp);
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
rs.close();
ps.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
return empList;
EmployeeDAOJDBCtemplateImpl.java
package com.journaldev.spring.jdbc.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import com.journaldev.spring.jdbc.model.Employee;
this.dataSource = dataSource;
@Override
String query = "insert into Employee (id, name, role) values (?,?,?)";
if (out != 0) {
} else
@Override
String query = "select id, name, role from Employee where id = ?";
//using RowMapper anonymous class, we can create a separate RowMapper for reuse
@Override
emp.setId(rs.getInt("id"));
emp.setName(rs.getString("name"));
emp.setRole(rs.getString("role"));
return emp;
});
return emp;
@Override
if (out != 0) {
} else
@Override
if (out != 0) {
} else
@Override
emp.setId(Integer.parseInt(String.valueOf(empRow.get("id"))));
emp.setName(String.valueOf(empRow.get("name")));
emp.setRole(String.valueOf(empRow.get("role")));
empList.add(emp);
return empList;
SpringMain.java
package com.journaldev.spring.jdbc.main;
import java.util.List;
import java.util.*;
import java.util.Random;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.journaldev.spring.jdbc.dao.EmployeeDAO;
import com.journaldev.spring.jdbc.model.Employee;
while (run != 0) {
switch (choice) {
case 1:
System.out.println("Enter id");
emp.setId(num);
emp.setName(name);
emp.setRole(job);
//Create
employeeDAO.save(emp);
System.out.println("Added to database");
break;
case 2:
int id = sc1.nextInt();
break;
case 3:
//Update
emp.setRole("CEO");
employeeDAO.update(emp);
break;
case 4:
employeeDAO.deleteById(delid);
break;
case 5:
System.out.println(empList);
break;
ctx.close();
Employee.java
package com.journaldev.spring.jdbc.model;
return id;
this.id = id;
return name;
this.name = name;
return role;
this.role = role;
@Override
Spring.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="employeeDAO"
class="com.journaldev.spring.jdbc.dao.EmployeeDAOImpl">
</bean>
<bean id="employeeDAOJDBCTemplate"
class="com.journaldev.spring.jdbc.dao.EmployeeDAOJDBCTemplateImpl">
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"
value="com.mysql.jdbc.Driver" />
<property name="url"
value="jdbc:mysql://localhost:3306/EmployeeDB" />
</bean>
</beans>
Output:
Practical 9.2
Theory:
In Spring JdbcTemplate, you can use prepared statements to execute parameterized queries
efficiently. Prepared statements allow you to precompile a SQL statement and use placeholders for
parameters that can be set at runtime.
To create a prepared statement in Spring JdbcTemplate, you can use the PreparedStatementCreator
or PreparedStatementSetter interfaces. These interfaces allow you to set values on a
PreparedStatement provided by the JdbcTemplate class for each update in a batch using the same
SQL.
Setting Parameters:
Once you have created the prepared statement, you can set the parameter values using the setter
methods defined in the PreparedStatement class. The values are set using the set<Type> methods,
where <Type> corresponds to the data type of the parameter.
After setting the parameter values, you can execute the prepared statement using the
executeUpdate method to perform the SQL operation.
Code:
File Structure
Create Database
USE Nikhil;
name VARCHAR(100),
department VARCHAR(100),
salary DECIMAL(10, 2)
);
Pom.xml
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.3.10</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.10</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.10</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.10</version>
<scope>test</scope>
</dependency>
</dependencies>
SpringJdbcConfig.java
package com.example.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import javax.sql.DataSource;
@Configuration
@ComponentScan(basePackages = "com.example.dao")
@Bean
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/Nikhil;
dataSource.setUsername("root");
dataSource.setPassword("root");
return dataSource;
@Bean
EmployeeDAO.java
package com.example.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.sql.PreparedStatement;
@Repository
@Autowired
String sql = "INSERT INTO employee (id, name, department) VALUES (?, ?, ?)";
jdbcTemplate.update(connection -> {
PreparedStatement ps = connection.prepareStatement(sql);
ps.setInt(1, id);
ps.setString(2, name);
ps.setString(3, department);
return ps;
});
jdbcTemplate.update(connection -> {
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, name);
ps.setString(2, department);
ps.setInt(3, id);
return ps;
});
jdbcTemplate.update(connection -> {
PreparedStatement ps = connection.prepareStatement(sql);
ps.setInt(1, id);
return ps;
});
MainApp.java
package com.example;
import com.example.config.SpringJdbcConfig;
import com.example.dao.EmployeeDAO;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
Output:
Practical 9.3
Theory:
The ResultSetExtractor interface in Spring JDBC is a callback interface used by JdbcTemplate's query
methods. It is responsible for extracting results from a ResultSet without worrying about exception
handling, as SQLExceptions will be caught and handled by the calling JdbcTemplate. This interface is
mainly used within the JDBC framework itself. While a RowMapper is a simpler choice for ResultSet
processing, the ResultSetExtractor interface is suitable for cases where processing the entire
ResultSet at once is necessary.
Code:
Pom.xml
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.25</version> <!-- Choose the version that matches your Spring version -->
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.25</version> <!-- Choose the version that matches your Spring version -->
</dependency>
<dependency>
<groupId>com.mysql.cj</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
Create a Database
Use StudentsDB;
name VARCHAR(100),
age INT
);
INSERT INTO student (id, name, age) VALUES (1, 'John Doe', 22);
INSERT INTO student (id, name, age) VALUES (2, 'Jane Doe', 21);
INSERT INTO student (id, name, age) VALUES (3, 'Jim Beam', 23);
Student.java
package com.example;
this.id = id;
this.name = name;
this.age = age;
return id;
this.id = id;
return name;
this.name = name;
return age;
this.age = age;
@Override
StudentResultSetExtractor.java
package com.example;
import org.springframework.jdbc.core.ResultSetExtractor;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
@Override
while (rs.next()) {
int id = rs.getInt("id");
return students;
}}
StudentService.java
package com.example;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import javax.sql.DataSource;
import java.util.List;
Main.java
package com.example;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import javax.sql.DataSource;
import java.util.List;
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/StudentsDB");
dataSource.setUsername("root");
dataSource.setPassword("root");
students.forEach(System.out::println);
Output:
Practical 9.4
Aim: Write a program to demonstrate RowMapper interface to fetch the records from the
database.
Theory:
RowMapper is a callback interface that is called for each row and maps the row of relations with the
instances to the model(user-defined) class. Unlike ResultSetExtractor the RowMapper iterates the
ResultSet internally and adds the extracted data into a collection, And we do not need to write the
code for collections as we do in ResultSetExtractor. It has only one method mapRow() which takes
two arguments ResultSet and rowNumber respectively. In order to use RowMapper, we need to
implement this interface and provide the definition for mapRow() method.
Code:
CREATE TABLE User ( id INT PRIMARY KEY, name VARCHAR(100), email VARCHAR(100) );
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>6.1.14</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.1.14</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
Main.java
package com.example;
System.out.println(user);
User.java
package com.example;
// Constructor
this.id = id;
this.name = name;
this.email = email;
return id;
this.id = id;
return name;
this.name = name;
return email;
this.email = email;
@Override
UserDao.java
package com.example;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import java.util.List;
public UserDao() {
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
String sql = "SELECT id, name, email FROM users"; // Query to fetch users
// Query the database and map the result to User objects using the UserRowMapper
UserRowMapper.java
package com.example;
import org.springframework.jdbc.core.RowMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
@Override
int id = rs.getInt("id");
Output:
10.1. Aim: WAP to create a simple Spring Boot application that prints a message.
Theory:
A simple Spring Boot application is a basic web application built using the Spring Boot framework,
typically with minimal configuration and setup. It often includes a single endpoint to demonstrate
the functioning of the application.
Code:
File Structure
MessageController.java
package com.springboot.restful.app;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
return "Write a program to create a Simple spring Boot application that prints a message:= "+
"Hii Welcome to Spring Boot application";
SimpleSpringAppApplication.java
package com.springboot.restful.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
SpringApplication.run(SimpleSpringAppApplication.class, args);
// Print a message
Output:
Practical 10.2
Aim: Write a program to demonstrate RESTful Web Services with spring Boot.
Theory:
RESTful web services with Spring Boot are a powerful way to build scalable and evolvable APIs. By
leveraging the stackless features of REST, developers can create services that are backwards
compatible, evolvable, scalable, and securable. RESTful web services are not a standard, but an
approach that provides a set of constraints on architecture to help build web-scale systems. Spring
Boot provides excellent support for building RESTful web services, making it a popular choice for
enterprise applications.
Code:
o Packaging: Jar
o Type: Maven
o Java Version: 21
o Language: Java
o Artifact: com.springboot.app
Click Next
File Structure
Product.java
package com.springboot.restful.app;
return id;
this.id = id;
return name;
this.name = name;
return price;
this.price = price;
ProductController.java
package com.springboot.restful.app;
import com.springboot.restful.app.*;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/api/products")
@GetMapping
return products;
@GetMapping("/{id}")
@PostMapping
products.add(product);
return product;
@PutMapping("/{id}")
if (existingProduct != null) {
existingProduct.setName(product.getName());
existingProduct.setPrice(product.getPrice());
return existingProduct;
@PatchMapping("/{id}")
if (existingProduct != null) {
if (product.getName() != null) {
existingProduct.setName(product.getName());
if (product.getPrice() != 0) {
existingProduct.setPrice(product.getPrice());
return existingProduct;
@DeleteMapping("/{id}")
if (product != null) {
products.remove(product);
Output:
Insert product
Delete product
Practical 10.3
Code:
File Structure
Application.properties
spring.application.name=SpringBootDatabase
spring.datasource.url=jdbc:mysql://localhost:3306/employee
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect
Employee.java
package com.springbootdb.restful.app;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
@Entity
@Id
// Default constructor
public Employee() {
this.id = id;
this.name = name;
this.email = email;
return id;
this.id = id;
return name;
this.name = name;
return email;
this.email = email;
EmployeeController.java
package com.springbootdb.restful.app;
import com.springbootdb.restful.app.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/employees")
@Autowired
@GetMapping
return employeeRepository.findAll();
@PostMapping
return employeeRepository.save(employee);
@GetMapping("/{id}")
return employeeRepository.findById(id).orElse(null);
EmployeeRepository.java
package com.springbootdb.restful.app;
import com.springbootdb.restful.app.*;
import org.springframework.data.jpa.repository.JpaRepository;
SpringBootDatabaseApplication.java
package com.springbootdb.restful.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
SpringApplication.run(SpringBootDatabaseApplication.class, args);
Open Git Bash and run following command to test various HTTP methods:
-H "Content-Type: application/json" \
{"id":2,"name":"Aachal Shah","email":"[email protected]"}
-H "Content-Type: application/json" \
{"id":2,"name":"Aachal Shah","email":"[email protected]"}
Output: