0% found this document useful (0 votes)
5 views

08_Prajwal Dikshit_AdvJava_Rubrics

advance java practical

Uploaded by

project6iccs
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

08_Prajwal Dikshit_AdvJava_Rubrics

advance java practical

Uploaded by

project6iccs
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 188

Subject: Advanced Java Lab Code:MCAL12

Practical & Assignment On


Advanced Java
Submitted By
Prajwal Dikshit
Roll No: 08
Under Guidance of
“Prof. Rashmi Pathak”

Master Of Computer Application


(MCA)

Name: Prajwal Dikshit 1|Page


Subject: Advanced Java Lab Code:MCAL12

Name: Prajwal Dikshit 2|Page


Subject: Advanced Java Lab Code:MCAL12

Practical Problem Statement Page Date


No
1 Assignments on Java Generics 6-17 27/09/24
1. Write a Java Program to demonstrate a Generic Class.
2. Write a Java Program to demonstrate Generic Methods.
3. Write a Java Program to demonstrate Wildcards in Java
Generics.
2 Assignments on List Interface 18-21 27/09/24
1. 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.
2. 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 / backward direction.
3 Assignments on Set Interface 21-25 27/09/24
1. Write a Java program to create a Set containing list of
items of type String and print the items in the list using
Iterator interface. Also print the list in reverse / backward
direction.
2. 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
4 Assignments on Map Interface 25-27 04/10/24
1. Write a Java program using Map interface containing
list of items
having keys and associated values and perform the
following
operations:
a. Add items in the map.
b. Remove items from the map
c. Search specific key from the map
d. Get value of the specified key
e. Insert map elements of one map in to other
map.
f. Print all keys and values of the map.

5 Assignments on Lambda Expression 28-38 04/10/24

Name: Prajwal Dikshit 3|Page


Subject: Advanced Java Lab Code:MCAL12

1. WAP using Lambda Expression to print “Hello


World”. .
2. WAP using Lambda Expression with single parameters.
3. Write a Java program using Lambda Expression with
multiple
parameters to add two numbers.
4. Write a Java program using Lambda Expression to
calculate the
following:
a. Convert Fahrenheit to Celsius
b. Convert Kilometers to Miles
5. Write a Java program using Lambda Expression with or
without
return keyword.
6. Write a Java program using Lambda Expression to
concatenate two strings.
6 Assignments based on web application development 39-72 08/11/24
using JSP
1. 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.
2. Write a JSP page to display the Registration form (Make
your ownassumptions)
3. Write a JSP program to add, delete and display the
records from
StudentMaster (RollNo, Name, Semester, Course) table.
4. 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%
5. 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.
6. Write a JSP program that demonstrates the use of JSP
declaration, scriptlet, directives, expression, header and
footer.
7 Assignment based on Spring Framework 77-96 8/11/24
1. Write a program to print “Hello World” using spring
framework.
2. Write a program to demonstrate dependency injection
via setter
method.

Name: Prajwal Dikshit 4|Page


Subject: Advanced Java Lab Code:MCAL12

3. Write a program to demonstrate dependency injection


via Constructor.
4. Write a program to demonstrate Autowiring.
8 Assignment based Aspect Oriented Programming 98-126 13/11/24
1. Write a program to demonstrate Spring AOP – before
advice.

2. Write a program to demonstrate Spring AOP – after


advice.
3. Write a program to demonstrate Spring AOP – around
advice.
4. Write a program to demonstrate Spring AOP – after
returning advice.
5. Write a program to demonstrate Spring AOP – after
throwing advice.
6. Write a program to demonstrate Spring AOP –
pointcuts.
9 Assignment based Spring JDBC 127-197 30/11/24
1. Write a program to insert, update and delete records
from the given table.
2. Write a program to demonstrate PreparedStatement in
Spring
JdbcTemplate
3. Write a program in Spring JDBC to demonstrate
ResultSetExtractor Interface
4. Write a program to demonstrate RowMapper interface
to fetch the records from the database.
10 Assignment based Spring Boot and RESTful Web 198-187 04/12/24
Services
1. Write a program to create a simple Spring Boot
application that prints a message.
2. Write a program to demonstrate RESTful Web Services
with spring boot.
3. Write a program to demonstrate Database Connection
with spring boot.

Name: Prajwal Dikshit 5|Page


Subject: Advanced Java Lab Code:MCAL12

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.

Source Code: // A Generic class with a single type parameter T


class Box<T> {
// Variable of type T
private T value;

// Constructor to initialize the value


public Box(T value) {
this.value = value;

Name: Prajwal Dikshit 6|Page


Subject: Advanced Java Lab Code:MCAL12

// Getter method to retrieve the value


public T getValue() {
return value;
}

// Setter method to set a new value


public void setValue(T value) {
this.value = value;
}

// Display the type of the generic value


public void displayType() {
System.out.println("Type of T is: " + value.getClass().getName());
}
}

public class GenericDemo {


public static void main(String[] args) {
// Creating a Box to hold an Integer
Box<Integer> integerBox = new Box<>(123);
integerBox.displayType(); // Should print: Type of T is:
java.lang.Integer
System.out.println("Value in integerBox: " + integerBox.getValue());

// Creating a Box to hold a String


Box<String> stringBox = new Box<>("Hello, Generics!");
stringBox.displayType(); // Should print: Type of T is:
java.lang.String
System.out.println("Value in stringBox: " + stringBox.getValue());

// Creating a Box to hold a Double


Box<Double> doubleBox = new Box<>(45.67);
doubleBox.displayType(); // Should print: Type of T is:
java.lang.Double
System.out.println("Value in doubleBox: " + doubleBox.getValue());
}
}

Name: Prajwal Dikshit 7|Page


Subject: Advanced Java Lab Code:MCAL12

Output:

Name: Prajwal Dikshit 8|Page


Subject: Advanced Java Lab Code:MCAL12

b) Aim: Write a Java Program to demonstrate Generic Methods.


Theory: Generic Method: printArray(T[] array):
o This method accepts an array of any type (T[]), prints each element, and
demonstrates how generic methods work.
o The method is declared with the generic type <T>, which allows it to
handle
different types of arrays (e.g., Integer, String, Double).
• Generic Method: findMaximum(T x, T y, T z):
o This method finds the maximum of three comparable values of any type
(T),
such as Integer, Double, or String.
o The generic type T is restricted to types that implement the
Comparable<T>
interface, ensuring that the compareTo() method can be used to compare
values.
o The method compares the values and returns the maximum one.
• Main Method:
o The printArray() method is demonstrated with different types of arrays
(Integer, String, and Double), showcasing how the same generic method
can
work with various types.
o The findMaximum() method is used with Integer, Double, and String
values, demonstrating how it compares values of different types and returns
the maximum.

Source Code: public class GenericMethodDemo {


// A generic method that accepts any type of array and prints its elements
public static <T> void printArray(T[] array) {
for (T element : array) {
System.out.print(element + " ");
}
System.out.println();
}

// A generic method to find the maximum of three comparable values


public static <T extends Comparable<T>> T findMaximum(T x, T y, T
z) {
T max = x; // Assume x is initially the maximum
if (y.compareTo(max) > 0) {
max = y; // y is the maximum so far

Name: Prajwal Dikshit 9|Page


Subject: Advanced Java Lab Code:MCAL12

}
if (z.compareTo(max) > 0) {
max = z; // z is the maximum so far
}
return max; // Return the maximum value
}

public static void main(String[] args) {


// Demonstrate printArray with different types of arrays
Integer[] intArray = {1, 2, 3, 4, 5};
String[] stringArray = {"Apple", "Banana", "Cherry"};
Double[] doubleArray = {1.1, 2.2, 3.3, 4.4};

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

// Demonstrate findMaximum with Integer values


System.out.println("Maximum of 3, 4, and 5: " + findMaximum(3, 4,
5));

// Demonstrate findMaximum with Double values


System.out.println("Maximum of 6.6, 8.8, and 7.7: " +
findMaximum(6.6, 8.8, 7.7));

// Demonstrate findMaximum with String values


System.out.println("Maximum of 'Apple', 'Banana', and 'Cherry': " +
findMaximum("Apple", "Banana", "Cherry"));
}
}

Name: Prajwal Dikshit 10 |


Page
Subject: Advanced Java Lab Code:MCAL12

Output:

Name: Prajwal Dikshit 11 |


Page
Subject: Advanced Java Lab Code:MCAL12

c) Aim: Write a Java Program to demonstrate Wildcards

Theory: Upper Bounded Wildcard (List<? extends Number>):


o The printNumbers() method uses the upper bounded wildcard ? extends
Number, which allows the method to accept a list of any type that is a
subclass of Number (like Integer, Double, Float, etc.).
o It can read elements from the list, but we cannot add elements to the list
since the exact type of ? is unknown.
• Unbounded Wildcard (List<?>):
o The printList() method uses the unbounded wildcard ?, which allows the
method to accept a list of any type (e.g., Integer, String, Double).
o It can read elements as Object but cannot add elements to the list.
• Lower Bounded Wildcard (List<? super Integer>):
o The addNumbers() method uses the lower bounded wildcard ? super
Integer, which means the list can accept Integer and any of its
superclasses (like Number or Object).
o We can add Integer elements to the list, but reading from the list can only
return Object since the exact type above Integer is unknown.
• Main Method:
o The program demonstrates wildcards by calling the methods with lists of
different types (e.g., Integer, Double, String).
o The program shows how wildcards make methods more flexible while
maintaining type safety, enabling them to work with different types of data
without needing multiple overloaded methods.

SourceCode: import java.util.ArrayList;


import java.util.List;
public class WildcardDemo {
// Method with an upper bounded wildcard that accepts only Number or its
subclasses
public static void printNumbers(List<? extends Number> list) {
for (Number number : list) {
System.out.print(number + " ");
}
System.out.println();
}
// Method with an unbounded wildcard that accepts a list of any type

Name: Prajwal Dikshit 12 |


Page
Subject: Advanced Java Lab Code:MCAL12

public static void printList(List<?> list) {


for (Object element : list) {
System.out.print(element + " ");
}
System.out.println();
}

// Method with a lower bounded wildcard that accepts Number or its


superclasses
public static void addNumbers(List<? super Integer> list) {
// We can add Integer values to this list
list.add(10);
list.add(20);
list.add(30);
}

public static void main(String[] args) {


// List of Integers
List<Integer> integerList = new ArrayList<>();
integerList.add(1);
integerList.add(2);
integerList.add(3);

// 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");

// Demonstrate upper bounded wildcard (List<? extends Number>)


System.out.println("Printing numbers (Integer List):");
printNumbers(integerList); // Should work because Integer is a
subclass of Number

Name: Prajwal Dikshit 13 |


Page
Subject: Advanced Java Lab Code:MCAL12

System.out.println("Printing numbers (Double List):");


printNumbers(doubleList); // Should work because Double is a
subclass of Number

// Demonstrate unbounded wildcard (List<?>)


System.out.println("Printing any type (Integer List):");
printList(integerList); // Should work for any type

System.out.println("Printing any type (String List):");


printList(stringList); // Should work for any type

// Demonstrate lower bounded wildcard (List<? super Integer>)


System.out.println("Adding numbers to a list with lower bound
wildcard (Integer
List):");
addNumbers(integerList); // Can add Integers because it is within
the bound
printList(integerList); // Print the list after adding
// We cannot add elements to `doubleList` because Double is not a
superclass of
Integer
}
}

Name: Prajwal Dikshit 14 |


Page
Subject: Advanced Java Lab Code:MCAL12

Name: Prajwal Dikshit 15 |


Page
Subject: Advanced Java Lab Code:MCAL12

Output:

Name: Prajwal Dikshit 16 |


Page
Subject: Advanced Java Lab Code:MCAL12

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");

Name: Prajwal Dikshit 17 |


Page
Subject: Advanced Java Lab Code:MCAL12

// Using a for-each loop to iterate over the list


for (String item : items) {
System.out.println(item);
}
}
}

Output:

Name: Prajwal Dikshit 18 |


Page
Subject: Advanced Java Lab Code:MCAL12

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());
}
}

Name: Prajwal Dikshit 19 |


Page
Subject: Advanced Java Lab Code:MCAL12

Output:

Name: Prajwal Dikshit 20 |


Page
Subject: Advanced Java Lab Code:MCAL12

Practical No:03 Assignments on Set Interface


a)Aim: Write a Java program to create a Set containing list of items of type
String and print
SourcCode: import java.util.Set;
import java.util.HashSet;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
// Creating a Set of Strings
Set<String> items = new HashSet<>();
// Adding items to the Set
items.add("Apple");
items.add("Banana");
items.add("Mango");
items.add("Orange");
// Using an Iterator to iterate over the Set
System.out.println("Items in the Set using Iterator:");
Iterator<String> iterator = items.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
// Converting Set to List to allow reverse order traversal
List<String> itemList = new ArrayList<>(items);

Name: Prajwal Dikshit 21 |


Page
Subject: Advanced Java Lab Code:MCAL12

// Printing the List in reverse order


System.out.println("\nItems in reverse order:");
Collections.reverse(itemList);
for (String item : itemList) {
System.out.println(item);
}
}
}

Output:

Name: Prajwal Dikshit 22 |


Page
Subject: Advanced Java Lab Code:MCAL12

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);

Name: Prajwal Dikshit 23 |


Page
Subject: Advanced Java Lab Code:MCAL12

System.out.println("Set 1 after inserting items from Set 2: " + set1);


// c. Remove an item from the set
set1.remove("Banana");
System.out.println("Set 1 after removing 'Banana': " + set1);
// d. Search for a specific item in the set
String searchItem = "Apple";
if (set1.contains(searchItem)) {
System.out.println(searchItem + " is found in the set.");
} else {
System.out.println(searchItem + " is not found in the set.");
}
}
}

Output:

Name: Prajwal Dikshit 24 |


Page
Subject: Advanced Java Lab Code:MCAL12

Practical No:04 Assignment on Map interface


Aim: Write a Java program using Map interface containing list of items having
keys and
associated values and perform the following operations:
a. Add items in the map.
b. Remove items from the map
c. Search specific key from the map
d. Get value of the specified key
e. Insert map elements of one map in to another map.
f. Print all keys and values of the map.
SoureCode: import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
// Creating a Map of String keys and Integer values
Map<String, Integer> map1 = new HashMap<>();
// a. Add items to the map
map1.put("Apple", 50);
map1.put("Banana", 20);
map1.put("Mango", 30);
map1.put("Orange", 40);
System.out.println("Map 1 after adding items: " + map1);
// b. Remove an item from the map
map1.remove("Banana");

Name: Prajwal Dikshit 25 |


Page
Subject: Advanced Java Lab Code:MCAL12

System.out.println("Map 1 after removing 'Banana': " + map1);


// c. Search for a specific key in the map
String searchKey = "Mango";
if (map1.containsKey(searchKey)) {
System.out.println(searchKey + " is found in the map.");
} else {
System.out.println(searchKey + " is not found in the map.");
}
// d. Get value associated with a specified key
String key = "Apple";
Integer value = map1.get(key);
if (value != null) {
System.out.println("Value associated with key '" + key + "' is: " + value);
} else {
System.out.println("Key '" + key + "' not found in the map.");
}
// e. Insert elements of one map into another map
Map<String, Integer> map2 = new HashMap<>();
map2.put("Grapes", 60);
map2.put("Pineapple", 80);
map1.putAll(map2);
System.out.println("Map 1 after inserting items from Map 2: " + map1);
// f. Print all keys and values of the map
System.out.println("\nAll keys and values in Map 1:");
for (Map.Entry<String, Integer> entry : map1.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}

Name: Prajwal Dikshit 26 |


Page
Subject: Advanced Java Lab Code:MCAL12

}
}

Output:

Name: Prajwal Dikshit 27 |


Page
Subject: Advanced Java Lab Code:MCAL12

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();

Name: Prajwal Dikshit 28 |


Page
Subject: Advanced Java Lab Code:MCAL12

}
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:

Name: Prajwal Dikshit 29 |


Page
Subject: Advanced Java Lab Code:MCAL12

b) Aim:Write a Java program using Lambda Expression with single


parameters.
Theory: Functional Interface (Greeting):
o We define a functional interface Greeting with a single abstract method
sayHello(String name) that takes one parameter, name. A functional
interface allows us to use lambda expressions.
o The @FunctionalInterface annotation is optional but helps ensure that
the interface contains only one abstract method.
• Lambda Expression:
o The lambda expression (name) -> System.out.println("Hello, " +
name) implements the sayHello method of the Greeting interface. It takes
a single parameter name and prints a greeting message.
o If the parameter type can be inferred, parentheses around the parameter
can
be omitted. For instance, name -> System.out.println("Hello, " +
name) is also valid.
• Main Method:
o In the main() method, we assign the lambda expression to the variable
greet of type Greeting.
o We call greet.sayHello("NIKHIL") and greet.sayHello("NAIK") to
print personalized greeting messages.

SourceCode: @FunctionalInterface
interface Greeting {
void sayHello(String name);
}

public class LambdaWithSingleParameter {


public static void main(String[] args) {
// Lambda expression with a single parameter
Greeting greet = (name) -> System.out.println("Hello, " + name);

// Calling the method to greet with a name


greet.sayHello("Rashmi");
greet.sayHello("John");

Name: Prajwal Dikshit 30 |


Page
Subject: Advanced Java Lab Code:MCAL12

}
}

Output:

c) Aim: Write a Java program using Lambda Expression with multiple


parameters to add two numbers.

Theory: Functional Interface (AddNumbers):


o We define a functional interface AddNumbers with a single abstract
method
add(int a, int b) that takes two parameters and returns an integer. This
functional interface allows us to use lambda expressions with two
parameters.
o The @FunctionalInterface annotation is optional but ensures that the
interface has only one abstract method.
• Lambda Expression:
o The lambda expression (a, b) -> a + b provides the implementation for
the add() method of the AddNumbers interface. It takes two parameters a
and b, adds them, and returns the result.
o Since the return type can be inferred by the compiler, we don’t need to
explicitly use the return keyword or specify the parameter types.
• Main Method:

Name: Prajwal Dikshit 31 |


Page
Subject: Advanced Java Lab Code:MCAL12

o In the main() method, we assign the lambda expression to the variable


add
of type AddNumbers.
o We then call add.add(10, 20) and add.add(50, 30) to calculate the
sum of two numbers and print the result.

SourceCode: @FunctionalInterface
interface AddNumbers {
int add(int a, int b);
}

public class LambdaWithMultipleParameters {


public static void main(String[] args) {
// Lambda expression with two parameters (a, b) to add two numbers
AddNumbers add = (a, b) -> a + 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:

Name: Prajwal Dikshit 32 |


Page
Subject: Advanced Java Lab Code:MCAL12

d) Aim: Write a Java program using Lambda Expression to calculate the


following:
a. Convert Fahrenheit to Celcius
b. Convert Kilometers to Miles.

Theory: Functional Interface (Converter):


o We define a functional interface Converter with a single abstract
method
convert(double input) that takes one parameter and returns a double.
This interface allows us to use lambda expressions to perform the
conversions.
• Lambda Expression for Fahrenheit to Celsius:
o The lambda expression (fahrenheit) -> (fahrenheit - 32) * 5 / 9
implements the formula to convert Fahrenheit to Celsius.
o The formula used is: Celsius=(Fahrenheit−32)×59\text{Celsius} =
(\text{Fahrenheit} - 32) \times \frac{5}{9}Celsius=(Fahrenheit−32)×95
• Lambda Expression for Kilometers to Miles:
o The lambda expression (kilometers) -> kilometers * 0.621371
implements the formula to convert kilometers to miles.
o The conversion factor is: 1 Kilometer=0.621371 Miles1 \,
\text{Kilometer} =
0.621371 \, \text{Miles}1Kilometer=0.621371Miles
• Main Method:
o We create two lambda expressions, fahrenheitToCelsius and
kilometersToMiles, to handle the conversions.
o We convert 98.6 Fahrenheit to Celsius and 10 kilometers to miles, and
print
the results.

Source Code: @FunctionalInterface


interface Converter {
double convert(double input);
}
public class LambdaUnitConversion {
public static void main(String[] args) {
// Lambda expression to convert Fahrenheit to Celsius

Name: Prajwal Dikshit 33 |


Page
Subject: Advanced Java Lab Code:MCAL12

Converter fahrenheitToCelsius = (fahrenheit) -> (fahrenheit - 32) * 5


/ 9;

// Lambda expression to convert Kilometers to Miles


Converter kilometersToMiles = (kilometers) -> kilometers *
0.621371;

// Convert Fahrenheit to Celsius


double fahrenheit = 98.6;
double celsius = fahrenheitToCelsius.convert(fahrenheit);
System.out.println(fahrenheit + " Fahrenheit is " + celsius + "
Celsius");

// Convert Kilometers to Miles


double kilometers = 10.0;
double miles = kilometersToMiles.convert(kilometers);
System.out.println(kilometers + " Kilometers is " + miles + "
Miles");
}
}

Output:

Name: Prajwal Dikshit 34 |


Page
Subject: Advanced Java Lab Code:MCAL12

e) Aim: Write a Java program using Lambda Expression with or without


return keyword.

Theory: Functional Interface (Adder):


o We define a functional interface Adder with a single abstract method
add(int a, int b). This interface will be implemented by our lambda
expressions.
• Lambda Expression without return:
o The first lambda expression Adder addWithoutReturn = (a, b) -> a +
b; is a single-line expression where the return keyword is not needed. The
result is implicitly returned.
o For simple operations, the lambda can omit the return keyword and
curly
braces.
• Lambda Expression with return:
o The second lambda expression Adder addWithReturn = (a, b) ->
{ return a + b; }; uses the return keyword because it's a block of
code enclosed in curly braces. The return keyword is explicitly needed
when using curly braces.
o This allows more flexibility if you want to add multiple lines of code
inside the
lambda body.
• Main Method:
o We use both lambda expressions to add two numbers and store the
results
in result1 and result2.
o Finally, the results are printed.

Source Code: @FunctionalInterface


interface Adder {
int add(int a, int b);
}
public class LambdaWithAndWithoutReturn {
public static void main(String[] args) {
// Lambda expression without return keyword (single-line expression)

Name: Prajwal Dikshit 35 |


Page
Subject: Advanced Java Lab Code:MCAL12

Adder addWithoutReturn = (a, b) -> a + b;


// Lambda expression with return keyword (block of code)
Adder addWithReturn = (a, b) -> {
return a + b;
};

// Testing both lambda expressions


int result1 = addWithoutReturn.add(10, 20);
int result2 = addWithReturn.add(15, 25);

// Output the results


System.out.println("Result without return keyword: " + result1);
System.out.println("Result with return keyword: " + result2);
}
}

Output:

Name: Prajwal Dikshit 36 |


Page
Subject: Advanced Java Lab Code:MCAL12

f) Aim: Write a Java program using Lambda Expression to concatenate two


strings.

Theory: Functional Interface (Concatenator):


o We define a functional interface Concatenator with a single abstract
method concatenate(String s1, String s2). This method takes two
strings as parameters and returns a concatenated string.
o The @FunctionalInterface annotation is used to ensure that only one
abstract method is defined, allowing us to use lambda expressions.
2. Lambda Expression:
o The lambda expression (s1, s2) -> s1 + s2 provides the
implementation for the concatenate() method. It takes two string
parameters s1 and s2 and returns their concatenation.
o This expression replaces the need for creating an anonymous class or
method implementation.
3. Main Method:
o In the main() method, we assign the lambda expression to the variable
concat of type Concatenator.
o We then call the concatenate() method twice, passing two strings each
time, and print the result.
Source Code: @FunctionalInterface
interface Concatenator {
String concatenate(String s1, String s2);
}

public class LambdaStringConcatenation {


public static void main(String[] args) {
// Lambda expression to concatenate two strings
Concatenator concat = (s1, s2) -> s1 + s2;

// Concatenate two strings and print the result


String result = concat.concatenate("Hello, ", "World!");
System.out.println("Concatenated String: " + result);

// Another example

Name: Prajwal Dikshit 37 |


Page
Subject: Advanced Java Lab Code:MCAL12

String result2 = concat.concatenate("Lambda ", "Expression");


System.out.println("Concatenated String: " + result2);
}
}

Output:

Name: Prajwal Dikshit 38 |


Page
Subject: Advanced Java Lab Code:MCAL12

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

The lifecycle of a JSP page consists of the following phases:

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.

Components of a JSP Page

 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>.

Name: Prajwal Dikshit 39 |


Page
Subject: Advanced Java Lab Code:MCAL12

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" %>.

JSP Scripting Elements

 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

 jsp:include: Includes another resource at request time. Example: <jsp:include


page="header.jsp" />.
 jsp:forward: Forwards the request to another resource. Example: <jsp:forward
page="login.jsp" />.
 jsp:useBean: Instantiates or references a JavaBean. Example: <jsp:useBean id="user"
class="com.example.User" />.

Setting Up JSP Environment

1. Web Server: Use a servlet container like Apache Tomcat.


2. IDE: Integrated Development Environments like Eclipse or IntelliJ IDEA simplify JSP
development.
3. Database: Use JDBC (Java Database Connectivity) to connect JSP pages to databases.

Deploying JSP Applications

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).

Name: Prajwal Dikshit 40 |


Page
Subject: Advanced Java Lab Code:MCAL12

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

Source Code: Step 1: Set Up the Project in Eclipse


1. Create a Dynamic Web Project:
o Open Eclipse.
o Go to File > New > Dynamic Web Project.
o Name the project (e.g., TelephoneDirectory).
o Set the Target runtime to the appropriate version of Tomcat
(Tomcat 9 or 10).
o Set the Dynamic Web Module version to 3.1 or 4.0 depending on
your Tomcat version.
o Click Finish.
2. Add the Required Libraries:
o If you are using Tomcat 10 (Jakarta EE), add the jakarta.servlet-
api.jar to your lib folder.
o If using Tomcat 9, add javax.servlet-api.jar to lib.
Step 2: Create Database and Table
Create a database and a table to store contact details.
1. Database Configuration:
o Use MySQL or any other database of your choice.
o Create a database named telephone_directory.
2. Create a Table:
sql
CREATE TABLE contacts (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
phone VARCHAR(15),
email VARCHAR(100)
);
Step 3: Create DBConnection Class
The DBConnection class is responsible for establishing a connection to
the database.

Name: Prajwal Dikshit 41 |


Page
Subject: Advanced Java Lab Code:MCAL12

1. Create the DBConnection Class:


o Create a package com.telephonedirectory in your src/main/java
directory.
o Create a DBConnection.java class in that package.
java
package com.telephonedirectory;

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

Name: Prajwal Dikshit 42 |


Page
Subject: Advanced Java Lab Code:MCAL12

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>
<%
}

Name: Prajwal Dikshit 43 |


Page
Subject: Advanced Java Lab Code:MCAL12

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>

<form action="addcontact.jsp" method="post">


Name: <input type="text" name="name" required><br>
Phone: <input type="text" name="phone" required><br>
Email: <input type="email" name="email" required><br>
<input type="submit" value="Add Contact">
</form>
<%
String name = request.getParameter("name");
String phone = request.getParameter("phone");
String email = request.getParameter("email");

if (name != null && phone != null && email != null) {


Connection conn = DBConnection.getConnection();
PreparedStatement ps = conn.prepareStatement("INSERT INTO
contacts (name, phone, email) VALUES (?, ?, ?)");
ps.setString(1, name);
ps.setString(2, phone);
ps.setString(3, email);

Name: Prajwal Dikshit 44 |


Page
Subject: Advanced Java Lab Code:MCAL12

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.

Name: Prajwal Dikshit 45 |


Page
Subject: Advanced Java Lab Code:MCAL12

Output:

Name: Prajwal Dikshit 46 |


Page
Subject: Advanced Java Lab Code:MCAL12

Practical 6.2

Aim: Write a JSP page to display the Registration form (Make your own assumptions)

Code:

Index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Registration Form</title>

<style>

*{

margin: 0;

padding: 0;

Name: Prajwal Dikshit 47 |


Page
Subject: Advanced Java Lab Code:MCAL12

box-sizing: border-box;

html, body {

width: 100%;

height: 100%;

.contact {

padding: 60px 20px;

.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;

box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);

.contact-form label {

display: block;

margin-bottom: 8px;

font-size: 1rem;

Name: Prajwal Dikshit 48 |


Page
Subject: Advanced Java Lab Code:MCAL12

.contact-form input, .contact-form textarea {

width: 100%;

padding: 10px;

margin-bottom: 15px;

border-radius: 4px;

border: 1px solid #ddd;

.contact-form button {

background-color: #f5a623;

color: #fff;

padding: 10px 20px;

border: none;

border-radius: 5px;

font-size: 1rem;

cursor: pointer;

transition: background-color 0.3s ease;

.contact-form button:hover {

background-color: #e59423;

.contact-info {

margin-top: 20px;

text-align: center;

.contact-info p {

Name: Prajwal Dikshit 49 |


Page
Subject: Advanced Java Lab Code:MCAL12

font-size: 1rem;

margin: 5px 0;

.map {

height: 300px;

margin-top: 20px;

</style>

</head>

<body>

<section id="contact" class="contact">

<div class="container">

<h2>Registration Form</h2>

<form action="displayinfo.jsp" method="post" class="contact-form">

<label for="name">Name:</label> <input type="text" id="name"

name="name" required> <label for="email">Email:</label>


<input

type="email" id="email" name="email" required> <label

for="phone">Phone:</label> <input type="tel" id="phone"

name="phone" required> <label


for="company">Password:</label>

<input type="password" id="password" name="password">

<button type="submit" class="btn-primary">Submit</button>

<button type="reset" class="btn-primary">Reset</button>

</form>

</div>

</section>

Name: Prajwal Dikshit 50 |


Page
Subject: Advanced Java Lab Code:MCAL12

</body>

</html>

Displayinfo.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

</head>

<body>

<%

String uname = request.getParameter("name");

String email = request.getParameter("email");

Name: Prajwal Dikshit 51 |


Page
Subject: Advanced Java Lab Code:MCAL12

String password = request.getParameter("password");

String phone = request.getParameter("phone");

%>

<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>

Name: Prajwal Dikshit 52 |


Page
Subject: Advanced Java Lab Code:MCAL12

Output:

Name: Prajwal Dikshit 53 |


Page
Subject: Advanced Java Lab Code:MCAL12

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

<%@ include file="dbconnect.jsp" %>

<%@ page import="java.sql.*" %>

<html>

<head>

<title>Student Management</title>

</head>

<body>

<h2>Add Student Record</h2>

<form action="addStudent.jsp" method="post">

Roll No: <input type="text" name="rollno" /><br/>

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

Semester: <input type="text" name="semester" /><br/>

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

<input type="submit" value="Add Student" />

</form>

<h2>Delete Student Record</h2>

Name: Prajwal Dikshit 54 |


Page
Subject: Advanced Java Lab Code:MCAL12

<form action="deleteStudent.jsp" method="post">

Roll No: <input type="text" name="rollno" /><br/>

<input type="submit" value="Delete Student" />

</form>

<h2>Student Records</h2>

<%

Statement stmt = con.createStatement();

ResultSet rs = stmt.executeQuery("SELECT * FROM StudentMaster");

%>

<table border="1">

<tr>

<th>Roll No</th>

<th>Name</th>

<th>Semester</th>

<th>Course</th>

</tr>

<%

while (rs.next()) {

%>

<tr>

<td><%= rs.getInt("RollNo") %></td>

<td><%= rs.getString("Name") %></td>

<td><%= rs.getInt("Semester") %></td>

<td><%= rs.getString("Course") %></td>

</tr>

<%

%>

</table>

</body>

Name: Prajwal Dikshit 55 |


Page
Subject: Advanced Java Lab Code:MCAL12

</html>

addStudent.jsp

<%@ include file="dbconnect.jsp" %>

<%@ page import="java.sql.*" %>

<html>

<body>

<%

int rollno = Integer.parseInt(request.getParameter("rollno"));

String name = request.getParameter("name");

int semester = Integer.parseInt(request.getParameter("semester"));

Name: Prajwal Dikshit 56 |


Page
Subject: Advanced Java Lab Code:MCAL12

String course = request.getParameter("course");

String query = "INSERT INTO StudentMaster (RollNo, Name, Semester, Course) VALUES (?, ?, ?, ?)";

PreparedStatement pstmt = con.prepareStatement(query);

pstmt.setInt(1, rollno);

pstmt.setString(2, name);

pstmt.setInt(3, semester);

pstmt.setString(4, course);

int result = pstmt.executeUpdate();

if (result > 0) {

out.println("Student added successfully!");

} else {

out.println("Failed to add student!");

%>

<a href="index.jsp">Go Back</a>

</body>

</html>

Name: Prajwal Dikshit 57 |


Page
Subject: Advanced Java Lab Code:MCAL12

deleteStudent.jsp

<%@ include file="dbconnect.jsp" %>

<%@ page import="java.sql.*" %>

<html>

<body>

<%

int rollno = Integer.parseInt(request.getParameter("rollno"));

String query = "DELETE FROM StudentMaster WHERE RollNo=?";

PreparedStatement pstmt = con.prepareStatement(query);

pstmt.setInt(1, rollno);

int result = pstmt.executeUpdate();

if (result > 0) {

out.println("Student deleted successfully!");

} else {

out.println("Failed to delete student!");

%>

Name: Prajwal Dikshit 58 |


Page
Subject: Advanced Java Lab Code:MCAL12

<a href="index.jsp">Go Back</a>

</body>

</html>

dbconnect.jsp

<%@ page language="java" import="java.sql.*" %>

<%

String url = "jdbc:mysql://localhost:3306/student";

String username = "root";

String password = "root";

Connection con = null;

try {

Class.forName("com.mysql.jdbc.Driver");

con = DriverManager.getConnection(url, username, password);

out.println("Connected to the database");

} catch (Exception e) {

e.printStackTrace();

%>

Name: Prajwal Dikshit 59 |


Page
Subject: Advanced Java Lab Code:MCAL12

Output:

Name: Prajwal Dikshit 60 |


Page
Subject: Advanced Java Lab Code:MCAL12

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

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<html>

<head>

<title>Loan Calculator</title>

</head>

<body>

<h2>Loan Calculator</h2>

<form action="loanCalculator.jsp" method="post">

<label for="amount">Loan Amount (Principal): </label> <input

type="number" name="amount" required><br>

<br> <label for="years">Period of Time (in years): </label> <input

Name: Prajwal Dikshit 61 |


Page
Subject: Advanced Java Lab Code:MCAL12

type="number" name="years" required><br>

<br> <input type="submit" value="Calculate">

</form>

</body>

</html>

loanCalculator.jsp

<%@ page import="java.text.DecimalFormat"%>

<%@ page import="java.util.ArrayList"%>

<%@ page import="java.util.List"%>

<html>

<head>

<title>Loan Payment Details</title>

</head>

<body>

<h2>Loan Payment Details</h2>

<%

// Retrieve inputs from the form

double principal = Double.parseDouble(request.getParameter("amount"));

int years = Integer.parseInt(request.getParameter("years"));

Name: Prajwal Dikshit 62 |


Page
Subject: Advanced Java Lab Code:MCAL12

// Determine the interest rate based on the loan period

double annualInterestRate;

if (years >= 1 && years <= 7) {

annualInterestRate = 5.35;

} else if (years >= 8 && years <= 15) {

annualInterestRate = 5.5;

} else if (years >= 16 && years <= 30) {

annualInterestRate = 5.75;

} else {

out.println("Invalid loan period. Please enter between 1 and 30 years.");

return;

// Convert annual interest rate to a monthly rate

double monthlyInterestRate = (annualInterestRate / 100) / 12;

// Total number of payments (months)

int totalPayments = years * 12;

// Calculate monthly payment using amortization formula

double monthlyPayment = principal * monthlyInterestRate * Math.pow(1 + monthlyInterestRate,


totalPayments)

/ (Math.pow(1 + monthlyInterestRate, totalPayments) - 1);

// Format numbers to two decimal places

DecimalFormat df = new DecimalFormat("#.##");

out.println("<h3>Loan Summary</h3>");

out.println("Principal Amount: $" + df.format(principal) + "<br>");

out.println("Loan Period: " + years + " years<br>");

out.println("Annual Interest Rate: " + annualInterestRate + "%<br>");

out.println("Monthly Payment: $" + df.format(monthlyPayment) + "<br><br>");

// Calculate the balance and interest for each payment

double balance = principal;

double totalInterestPaid = 0;

out.println("<h3>Payment Schedule</h3>");

Name: Prajwal Dikshit 63 |


Page
Subject: Advanced Java Lab Code:MCAL12

out.println("<table border='1'>");

out.println(

"<tr><th>Payment #</th><th>Monthly Payment</th><th>Interest Paid</th><th>Principal


Paid</th><th>Remaining Balance</th></tr>");

for (int i = 1; i <= totalPayments; i++) {

double interestPaid = balance * monthlyInterestRate;

double principalPaid = monthlyPayment - interestPaid;

balance -= principalPaid;

totalInterestPaid += interestPaid;

// Ensure balance doesn't go negative due to floating-point precision issues

if (balance < 0) {

balance = 0;

// Output the payment details

out.println("<tr><td>" + i + "</td><td>$" + df.format(monthlyPayment) + "</td>");

out.println("<td>$" + df.format(interestPaid) + "</td>");

out.println("<td>$" + df.format(principalPaid) + "</td>");

out.println("<td>$" + df.format(balance) + "</td></tr>");

out.println("</table>");

out.println("<br>Total Interest Paid: $" + df.format(totalInterestPaid));

%>

<br>

<br>

<a href="index.jsp">Go Back</a>

</body>

</html>

Name: Prajwal Dikshit 64 |


Page
Subject: Advanced Java Lab Code:MCAL12

Output:

Name: Prajwal Dikshit 65 |


Page
Subject: Advanced Java Lab Code:MCAL12

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:

Name: Prajwal Dikshit 66 |


Page
Subject: Advanced Java Lab Code:MCAL12

index.jsp

<%@ page contentType="text/html; charset=UTF-8" language="java"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Change of Study Center Application Form</title>

<style>

body {

font-family: Arial, sans-serif;

background-color: #f4f4f9;

padding: 20px;

.container {

width: 50%;

margin: 0 auto;

background-color: #ffffff;

padding: 20px;

border-radius: 8px;

box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);

h2 {

text-align: center;

label {

font-weight: bold;

Name: Prajwal Dikshit 67 |


Page
Subject: Advanced Java Lab Code:MCAL12

input[type="text"], input[type="textarea"], select {

width: 100%;

padding: 8px;

margin: 10px 0;

border: 1px solid #ccc;

border-radius: 4px;

input[type="submit"] {

background-color: #4CAF50;

color: white;

border: none;

padding: 12px 20px;

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>

Name: Prajwal Dikshit 68 |


Page
Subject: Advanced Java Lab Code:MCAL12

<body>

<div class="container">

<h2>Application for Change of Study Center</h2>

<form action="processForm.jsp" method="post">

<label for="studentId">Student ID:</label> <input type="text"

id="studentId" name="studentId" required> <label for="name">Name:</label>

<input type="text" id="name" name="name" required> <label

for="currentCenter">Current Study Center:</label> <input type="text"

id="currentCenter" name="currentCenter" required> <label

for="newCenter">New Study Center:</label> <input type="text"

id="newCenter" name="newCenter" required> <label

for="reason">Reason for Change:</label>

<textarea id="reason" name="reason" rows="4" required></textarea>

<input type="submit" value="Submit Application">

</form>

</div>

</body>

</html>

Name: Prajwal Dikshit 69 |


Page
Subject: Advanced Java Lab Code:MCAL12

ProcessForm.jsp

<%@ page contentType="text/html; charset=UTF-8" language="java"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Application Submission Confirmation</title>

</head>

<body>

<div class="container">

<h2>Application Submitted UnSuccessfully</h2>

<div class="details">

<p>

<strong>Student ID:</strong>

<%=request.getParameter("studentId")%></p>

<p>

<strong>Name:</strong>

Name: Prajwal Dikshit 70 |


Page
Subject: Advanced Java Lab Code:MCAL12

<%=request.getParameter("name")%></p>

<p>

<strong>Current Study Center:</strong>

<%=request.getParameter("currentCenter")%></p>

<p>

<strong>New Study Center:</strong>

<%=request.getParameter("newCenter")%></p>

<p>

<strong>Reason for Change:</strong>

<%=request.getParameter("reason")%></p>

</div>

<a href="index.jsp" class="back-btn">Back to Application Form</a>

</div>

</body>

</html>

Name: Prajwal Dikshit 71 |


Page
Subject: Advanced Java Lab Code:MCAL12

Output:

Name: Prajwal Dikshit 72 |


Page
Subject: Advanced Java Lab Code:MCAL12

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

<%@ page contentType="text/html; charset=UTF-8" language="java"%>

<!-- Page Directive -->

<%@ include file="header.jsp"%>

<!-- Include Header (Header Directive) -->

<html>

<head>

<title>JSP Demo</title>

</head>

<body>

<h2>Welcome to the JSP Demo</h2>

<p>This page demonstrates the use of various JSP features:</p>

<!-- JSP Declaration -->

<%!// Declaring a method in JSP declaration section

public String getWelcomeMessage() {

return "Hello from JSP Declaration!";

}%>

<p>

Message from JSP Declaration:

Name: Prajwal Dikshit 73 |


Page
Subject: Advanced Java Lab Code:MCAL12

<%=getWelcomeMessage()%></p>

<!-- JSP Scriptlet -->

<%

// JSP scriptlet to compute the current date

java.util.Date date = new java.util.Date();

out.println("Current Date and Time: " + date.toString());

%>

<!-- JSP Expression -->

<p>

JSP Expression:

<%="Current year: " + java.time.Year.now().getValue()%></p>

<p>This page also includes a header and a footer.</p>

<br />

<br />

<!-- JSP Scriptlet to display dynamic data -->

<%

String username = "Nikhil"; // Hardcoded username for demonstration

out.println("<p>Logged in as: " + username + "</p>");

%>

<br />

<br />

<p>Now let's demonstrate the footer:</p>

<!-- Include Footer (Footer Directive) -->

<%@ include file="footer.jsp"%>

<!-- Include Footer (Footer Directive) -->

</body>

</html>

Name: Prajwal Dikshit 74 |


Page
Subject: Advanced Java Lab Code:MCAL12

Header.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<title>Header - JSP Demo</title>

</head>

Name: Prajwal Dikshit 75 |


Page
Subject: Advanced Java Lab Code:MCAL12

<body>

<header>

<h1>Welcome to My JSP Application</h1>

</header>

</body>

</html>

Footer.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<body>

<footer>

<p>&copy; 2024 JSP Application. All rights reserved.</p>

</footer>

</body>

</html>

Name: Prajwal Dikshit 76 |


Page
Subject: Advanced Java Lab Code:MCAL12

Output:

Name: Prajwal Dikshit 77 |


Page
Subject: Advanced Java Lab Code:MCAL12

Practical 7 - Assignment based Spring Framework

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.

 It is a lightweight, loosely coupled and integrated framework.

 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>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-core</artifactId>

<version>6.1.14</version>

</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-context</artifactId>

<version>6.1.14</version>

</dependency>

</dependencies>

Name: Prajwal Dikshit 78 |


Page
Subject: Advanced Java Lab Code:MCAL12

Config.xml

<?xml version="1.0" encoding="UTF-8"?>

<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 id="t" class="com.helloWorld.helloWorld">

<property name="txt" value="Hello World!!" />

</bean>

</beans>

HelloWorld.java

package com.helloWorld;

public class helloWorld {

private String txt;

public String getTxt() {

return txt;

public void setTxt(String txt) {

Name: Prajwal Dikshit 79 |


Page
Subject: Advanced Java Lab Code:MCAL12

this.txt = txt;

Main.java

package com.helloWorld;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

public static void main(String[] args) {

// TODO Auto-generated method stub

ApplicationContext context = new ClassPathXmlApplicationContext("com/helloWorld/config.xml");

helloWorld txt = (helloWorld) context.getBean("t");

System.out.println(txt.getTxt());

Name: Prajwal Dikshit 80 |


Page
Subject: Advanced Java Lab Code:MCAL12

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>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-core</artifactId>

<version>6.1.14</version>

</dependency>

Name: Prajwal Dikshit 81 |


Page
Subject: Advanced Java Lab Code:MCAL12

<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-context</artifactId>

<version>6.1.14</version>

</dependency>

</dependencies>

Config.xml

<?xml version="1.0" encoding="UTF-8"?>

<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 id="mam" class="com.spring.dependency.Teacher">

<property name="name" value="Rashmi Mam" />

<property name="courseName" value="Adv Java" />

</bean>

<bean id="s1" class="com.spring.dependency.Student">

<property name="rollNumber" value="10" />

<property name="name" value="Bruce" />

<property name="teacher" ref="mam" />

</bean>

Name: Prajwal Dikshit 82 |


Page
Subject: Advanced Java Lab Code:MCAL12

</beans>

Main.java

package com.spring.dependency;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

public static void main(String[] args) {

ApplicationContext context = new

ClassPathXmlApplicationContext("com/spring/dependency/config.xml");

Student s = (Student) context.getBean("s1");

System.out.println(s);

Student.java

Name: Prajwal Dikshit 83 |


Page
Subject: Advanced Java Lab Code:MCAL12

package com.spring.dependency;

public class Student {

private int rollNumber;

private String name;

private Teacher teacher;

public Teacher getTeacher() {

return teacher;

public void setTeacher(Teacher teacher) {

this.teacher = teacher;

public int getRollNumber() {

return rollNumber;

public void setRollNumber(int rollNumber) {

this.rollNumber = rollNumber;

public String getName() {

return name;

public void setName(String name) {

this.name = name;

Name: Prajwal Dikshit 84 |


Page
Subject: Advanced Java Lab Code:MCAL12

@Override

public String toString() {

return "Student [rollNumber=" + rollNumber + ", name=" + name + ", teacher=" + teacher + "]";

Teacher.java

package com.spring.dependency;

public class Teacher {

private String name;

private String courseName;

public String getName() {

return name;

public void setName(String name) {

this.name = name;

Name: Prajwal Dikshit 85 |


Page
Subject: Advanced Java Lab Code:MCAL12

public String getCourseName() {

return courseName;

public void setCourseName(String courseName) {

this.courseName = courseName;

@Override

public String toString() {

return "Teacher [name=" + name + ", courseName=" + courseName + "]";

Output:

Practical 7.3

Aim: Write a program to demonstrate dependency injection via Constructor injection method.

Theory:

Name: Prajwal Dikshit 86 |


Page
Subject: Advanced Java Lab Code:MCAL12

 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.

 <constructor-arg> element describes one argument of the constructor, which means to


specify a constructor with multiple arguments we need to use <constructor-arg> element
multiple times.

Code:

Pom.xml

<dependencies>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-core</artifactId>

<version>6.1.14</version>

</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-context</artifactId>

<version>6.1.14</version>

</dependency>

</dependencies>

Name: Prajwal Dikshit 87 |


Page
Subject: Advanced Java Lab Code:MCAL12

Config.xml

<?xml version="1.0" encoding="UTF-8"?>

<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 id="mam" class="com.example.constructor.Teacher">

<constructor-arg value="Rashmi Mam" />

<constructor-arg value="Adv Java" />

</bean>

<bean id="s1" class="com.example.constructor.Student">

<constructor-arg value="Bruce" />

<constructor-arg value="10" />

<constructor-arg ref="mam" />

</bean>

</beans>

Name: Prajwal Dikshit 88 |


Page
Subject: Advanced Java Lab Code:MCAL12

Main.java

package com.example.constructor;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

public static void main(String[] args) {

ApplicationContext context = new


ClassPathXmlApplicationContext("com/spring/dependency/config.xml");

Student s = (Student) context.getBean("s1");

System.out.println(s);

Student.java

package com.example.constructor;

public class Student {

Name: Prajwal Dikshit 89 |


Page
Subject: Advanced Java Lab Code:MCAL12

private int rollNumber;

private String name;

private Teacher teacher;

public Student(int rollNumber, String name, Teacher teacher) {

super();

this.rollNumber = rollNumber;

this.name = name;

this.teacher = teacher;

@Override

public String toString() {

return "Student [rollNumber=" + rollNumber + ", name=" + name + ", teacher=" + teacher + "]";

Teacher.java

package com.example.constructor;

public class Teacher {

private String name;

Name: Prajwal Dikshit 90 |


Page
Subject: Advanced Java Lab Code:MCAL12

private String courseName;

public Teacher(String name, String courseName) {

super();

this.name = name;

this.courseName = courseName;

@Override

public String toString() {

return "Teacher [name=" + name + ", courseName=" + courseName + "]";

Output:

Name: Prajwal Dikshit 91 |


Page
Subject: Advanced Java Lab Code:MCAL12

Practical 7.4

Aim: Write a program to demonstrate Autowiring.

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>

Name: Prajwal Dikshit 92 |


Page
Subject: Advanced Java Lab Code:MCAL12

MessageService. Java (package)

package com.annotations;

public interface MessageService {

void sendMessage(String example);

AppConfig.java

package com.annotations;

import org.springframework.context.annotation.ComponentScan;

import org.springframework.context.annotation.Configuration;

@Configuration

@ComponentScan(basePackages = "com.annotations")

Name: Prajwal Dikshit 93 |


Page
Subject: Advanced Java Lab Code:MCAL12

public class AppConfig {

EmailService.java

package com.annotations;

import org.springframework.stereotype.Service;

@Service

public class EmailService implements MessageService{

@Override

public void sendMessage(String example) {

System.out.println("Email sent with this message: " +example);

NotificationController.java

package com.annotations;

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

import org.springframework.stereotype.Component;

Name: Prajwal Dikshit 94 |


Page
Subject: Advanced Java Lab Code:MCAL12

@Component

public class NotificationController {

private MessageService messageService;

public void setMessageService(MessageService messageService) {

this.messageService = messageService;

public MessageService getMessageService() {

return messageService;

// Constructor injection with @Autowired

@Autowired

public NotificationController(MessageService messageService) {

this.messageService = messageService;

public void notifyUser(String message) {

messageService.sendMessage(message);

Name: Prajwal Dikshit 95 |


Page
Subject: Advanced Java Lab Code:MCAL12

Main.java

package com.annotations;

import org.springframework.context.ApplicationContext;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {

public static void main(String[] args) {

ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);

NotificationController controller = applicationContext.getBean(NotificationController.class);

controller.notifyUser("Bruce");

Name: Prajwal Dikshit 96 |


Page
Subject: Advanced Java Lab Code:MCAL12

Output:

Practical No.8 - Assignment based Aspect Oriented Programming

Aim: Assignment based Aspect Oriented Programming

Practical 8.1. Write a program to demonstrate Spring AOP – before advice.

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.

 Following is the syntax of @Before advice.

@Before("selectGetName ()") public void beforeAdvice(){

System.out.println("Going to setup student profile.");

Code:

File Structure

Name: Prajwal Dikshit 97 |


Page
Subject: Advanced Java Lab Code:MCAL12

LoggingAspect.java

package com.springAopPract.beforeAdvice;

import org.aspectj.lang.annotation.Before;

public class LoggingAspect {

// Before Advice

@Before("execution(* com.example.service.SimpleService.performTask(..))")

public void beforeAdvice() {

System.out.println("Before Advice: Task is about to start.");

Name: Prajwal Dikshit 98 |


Page
Subject: Advanced Java Lab Code:MCAL12

Main.java

package com.springAopPract.beforeAdvice;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main{

public static void main(String[] args) {

ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");

SimpleService simpleService = context.getBean("simpleService", SimpleService.class);

System.out.println("Calling performTask()");

simpleService.performTask();

} }

SimpleService.java

package com.springAopPract.beforeAdvice;

public class SimpleService {

public void performTask() {

Name: Prajwal Dikshit 99 |


Page
Subject: Advanced Java Lab Code:MCAL12

System.out.println("Executing performTask() method.");

Spring-onfig.xml

<?xml version="1.0" encoding="UTF-8"?>

<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">

<!-- Enable AspectJ auto proxy -->

<aop:aspectj-autoproxy/>

<!-- Define service and aspect beans -->

<bean id="simpleService" class="com.springAopPract.beforeAdvice.SimpleService"/>

<bean id="loggingAspect" class="com.springAopPract.beforeAdvice.LoggingAspect"/>

</beans>

Name: Prajwal Dikshit 100 |


Page
Subject: Advanced Java Lab Code:MCAL12

Output:

Practical 8.2

Aim: Write a program to demonstrate Spring AOP – after advice.

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.

 Following is the syntax of @After advice.

@Aspect @Component public class LoggingAspect { @After("execution(*

com.example.FileSystemStorageService.writeFile(..))") public void logFileName(JoinPoint joinPoint) }

Code:

FileStructure:

Name: Prajwal Dikshit 101 |


Page
Subject: Advanced Java Lab Code:MCAL12

LoggingAspect.java

package com.afterAdvice;

import org.aspectj.lang.annotation.After;

import org.aspectj.lang.annotation.Aspect;

@Aspect

public class LoggingAspect {

// After (Finally) Advice

@After("execution(* com.afterAdvice.SimpleService.performTask(..))")

public void afterAdvice() {

System.out.println("After (Finally) Advice: Task has completed.");

Name: Prajwal Dikshit 102 |


Page
Subject: Advanced Java Lab Code:MCAL12

Main.java

package com.afterAdvice;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

public static void main(String[] args) {

ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");

SimpleService simpleService = context.getBean("simpleService", SimpleService.class);

System.out.println("Calling performTask()");

simpleService.performTask();

Name: Prajwal Dikshit 103 |


Page
Subject: Advanced Java Lab Code:MCAL12

SimpleService.java

package com.afterAdvice;

public class SimpleService {

public void performTask() {

System.out.println("Executing performTask() method.");

 spring-config.xml

<?xml version="1.0" encoding="UTF-8"?>

<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">

Name: Prajwal Dikshit 104 |


Page
Subject: Advanced Java Lab Code:MCAL12

<!-- Enable AspectJ auto proxy -->

<aop:aspectj-autoproxy/>

<!-- Define service and aspect beans -->

<bean id="simpleService" class="com.afterAdvice.SimpleService"/>

<bean id="loggingAspect" class="com.afterAdvice.LoggingAspect"/>

</beans>

Output:

Name: Prajwal Dikshit 105 |


Page
Subject: Advanced Java Lab Code:MCAL12

Practical 8.3

Aim: Write a program to demonstrate Spring AOP – around advice.

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.

 Following is the syntax of

@Around("execution(* com.example.MathService.factorial(..))") public Object


cacheFactorial(ProceedingJoinPoint pjp)

throws Throwable {

Object[] args = pjp.getArgs(); int n = (Integer) args[0];

if (cache.containsKey(n)) { return cache.get(n);

Code :

FileStructure:

LoggingAspect.java

package com.aroundAdvice;

import org.aspectj.lang.ProceedingJoinPoint;

import org.aspectj.lang.annotation.Around;

import org.aspectj.lang.annotation.Aspect;

Name: Prajwal Dikshit 106 |


Page
Subject: Advanced Java Lab Code:MCAL12

@Aspect

public class LoggingAspect {

// Around Advice

@Around("execution(* com.aroundAdvice.SimpleService.performTask(..))")

public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {

System.out.println("Around Advice: Before method execution");

// Proceed with the target method execution

Object result = joinPoint.proceed();

System.out.println("Around Advice: After method execution");

return result;

Main.java

package com.aroundAdvice;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

public static void main(String[] args) {

ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");

Name: Prajwal Dikshit 107 |


Page
Subject: Advanced Java Lab Code:MCAL12

SimpleService simpleService = context.getBean("simpleService", SimpleService.class);

System.out.println("Calling performTask()");

simpleService.performTask();

SimpleService.java

package com.aroundAdvice;

public class SimpleService {

public void performTask() {

System.out.println("Executing performTask() method.");

Spring-config.xml

<?xml version="1.0" encoding="UTF-8"?>

<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

Name: Prajwal Dikshit 108 |


Page
Subject: Advanced Java Lab Code:MCAL12

http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop.xsd">

<!-- Enable AspectJ auto proxy -->

<aop:aspectj-autoproxy/>

<!-- Define service and aspect beans -->

<bean id="simpleService" class="com.aroundAdvice.SimpleService"/>

<bean id="loggingAspect" class="com.aroundAdvice.LoggingAspect"/>

</beans>

Output:

Practical 8.4

Aim: Write a program to demonstrate Spring AOP – after returning advice.

Name: Prajwal Dikshit 109 |


Page
Subject: Advanced Java Lab Code:MCAL12

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.

 Following is the syntax. @AfterReturning(pointcut="execution(*

com.example.CalculationService.calculate(..))", returning = "result") public void logResult(JoinPoint


joinPoint, int result) { log.info("The result of {} is {}",

joinPoint.getSignature(), result);

}}

Code:

File Structure:

LoggingAspect.java

package com.afterReturningAdvice;

import org.aspectj.lang.annotation.AfterReturning;

import org.aspectj.lang.annotation.Aspect;

@Aspect

public class LoggingAspect {

// After Returning Advice

Name: Prajwal Dikshit 110 |


Page
Subject: Advanced Java Lab Code:MCAL12

@AfterReturning(pointcut = "execution(* com.afterReturningAdvice.SimpleService.getResult(..))",


returning = "result")

public void afterReturningAdvice(Object result) {

System.out.println("After Returning Advice: Result is " + result);

Main.java

package com.afterReturningAdvice;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

public static void main(String[] args) {

ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");

SimpleService simpleService = context.getBean("simpleService", SimpleService.class);

System.out.println("Calling getResult()");

String result = simpleService.getResult();

System.out.println("Result from getResult(): " + result);

Name: Prajwal Dikshit 111 |


Page
Subject: Advanced Java Lab Code:MCAL12

SimpleService.java

package com.afterReturningAdvice;

public class SimpleService {

public String getResult() {

System.out.println("Executing getResult() method.");

return "Task Completed";

Spring-config.xml

<?xml version="1.0" encoding="UTF-8"?>

<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">

<!-- Enable AspectJ auto proxy -->

Name: Prajwal Dikshit 112 |


Page
Subject: Advanced Java Lab Code:MCAL12

<aop:aspectj-autoproxy/>

<!-- Define service and aspect beans -->

<bean id="simpleService" class="com.afterReturningAdvice.SimpleService"/>

<bean id="loggingAspect" class="com.afterReturningAdvice.LoggingAspect"/>

</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>

Name: Prajwal Dikshit 113 |


Page
Subject: Advanced Java Lab Code:MCAL12

<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

Aim: Write a program to demonstrate Spring AOP – after throwing advice.

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.

 Following is the syntax.

@AfterThrowing (pointcut="execution (*com.example.FileSystemStora geService.readFile(..))",


throwing = "ex")

public void logException(JoinPoint joinPoint, Exception ex) { log.error("An exception occurred while
reading file: {}", joinPoint.getSignature(), ex);

sendEmail(ex.getMessage());}}

Name: Prajwal Dikshit 114 |


Page
Subject: Advanced Java Lab Code:MCAL12

Code:

File Structure

LoggingAspect.java

package com.afterAdvice;

import org.aspectj.lang.annotation.After;

import org.aspectj.lang.annotation.Aspect;

@Aspect

public class LoggingAspect {

// After (Finally) Advice

@After("execution(* com.afterAdvice.SimpleService.performTask(..))")

public void afterAdvice() {

System.out.println("After (Finally) Advice: Task has completed.");

Name: Prajwal Dikshit 115 |


Page
Subject: Advanced Java Lab Code:MCAL12

Main.java

package com.afterAdvice;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

public static void main(String[] args) {

ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");

SimpleService simpleService = context.getBean("simpleService", SimpleService.class);

System.out.println("Calling performTask()");

simpleService.performTask();

Name: Prajwal Dikshit 116 |


Page
Subject: Advanced Java Lab Code:MCAL12

SimpleService.java

package com.afterAdvice;

public class SimpleService {

public void performTask() {

System.out.println("Executing performTask() method.");

Config.xml

<?xml version="1.0" encoding="UTF-8"?>

<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">

Name: Prajwal Dikshit 117 |


Page
Subject: Advanced Java Lab Code:MCAL12

<!-- Enable AspectJ auto proxy -->

<aop:aspectj-autoproxy/>

<!-- Define service and aspect beans -->

<bean id="simpleService" class="com.afterAdvice.SimpleService"/>

<bean id="loggingAspect" class="com.afterAdvice.LoggingAspect"/>

</beans>

Output:

Name: Prajwal Dikshit 118 |


Page
Subject: Advanced Java Lab Code:MCAL12

Practical 8.6

Aim: Write a program to demonstrate Spring AOP – pointcuts.

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.

 Following is the syntax. @Pointcut("within(com.example.*)") public void anyMethod() {}


@Before("anyMethod()")

public void logBefore(JoinPoint joinPoint) { log.info("Before executing {}", joinPoint.getSignature()); }

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>

Name: Prajwal Dikshit 119 |


Page
Subject: Advanced Java Lab Code:MCAL12

<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>

<version>1.9.7</version> <!-- Check for the latest version -->

</dependency>

<dependency>

<groupId>org.slf4j</groupId>

<artifactId>slf4j-api</artifactId>

<version>1.7.32</version>

</dependency>

<!-- Logback for SLF4J binding -->

<dependency>

<groupId>ch.qos.logback</groupId>

<artifactId>lookback-classic</artifactId>

<version>1.2.6</version>

</dependency>

</dependencies>

Name: Prajwal Dikshit 120 |


Page
Subject: Advanced Java Lab Code:MCAL12

AppConfig.java

package com.example;

import org.springframework.context.annotation.ComponentScan;

import org.springframework.context.annotation.Configuration;

import org.springframework.context.annotation.EnableAspectJAutoProxy;

Name: Prajwal Dikshit 121 |


Page
Subject: Advanced Java Lab Code:MCAL12

@Configuration

@EnableAspectJAutoProxy // Enables AspectJ-based proxying in Spring

@ComponentScan(basePackages = "com.example") // Scans the package for beans and aspects

public class AppConfig {

CustomAnnotation.java

package com.example;

import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME) // Ensure it is available at runtime

public @interface CustomAnnotation {

MyPointcutAspect.java

package com.example;

Name: Prajwal Dikshit 122 |


Page
Subject: Advanced Java Lab Code:MCAL12

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

public class MyPointcutAspect {

// Pointcut to match methods in MyService class with any name

@Pointcut("execution(* com.example.MyService.*(..))")

public void allMethodsInMyService() {

// Pointcut to match methods with specific argument types

@Pointcut("execution(* com.example.MyService.methodWithArgs(int))")

public void methodWithIntArgument() {

// Pointcut to match methods with specific return type

@Pointcut("execution(String com.example.MyService.processMessage(..))")

public void methodReturningString() {

// Pointcut to match methods with specific annotations

@Pointcut("@annotation(com.example.CustomAnnotation)")

public void methodsWithCustomAnnotation() {

// Advice: Executed before any method in MyService class

@Before("allMethodsInMyService()")

public void beforeMethodInMyService() {

System.out.println("Before executing method in MyService");

// Advice: Executed before methodWithArgs(int)

Name: Prajwal Dikshit 123 |


Page
Subject: Advanced Java Lab Code:MCAL12

@Before("methodWithIntArgument()")

public void beforeMethodWithIntArg() {

System.out.println("Before executing method with int argument");

// Advice: Executed before method that returns String

@Before("methodReturningString()")

public void beforeMethodReturningString() {

System.out.println("Before executing method that returns a String");

// Advice: Executed before methods with CustomAnnotation

@Before("methodsWithCustomAnnotation()")

public void beforeMethodWithCustomAnnotation() {

System.out.println("Before executing method with CustomAnnotation");

Name: Prajwal Dikshit 124 |


Page
Subject: Advanced Java Lab Code:MCAL12

MyService.java

package com.example;

import org.springframework.stereotype.Component;

import com.example.CustomAnnotation;

@Component

public class MyService {

public void greeting(String name) {

System.out.println("Hello, " + name + "!");

public void farewell(String name) {

System.out.println("Goodbye, " + name + "!");

public String processMessage(String message) {

System.out.println("Processing message: " + message);

return "Processed: " + message;

public void methodWithArgs(int age) {

System.out.println("Age is: " + age);

@CustomAnnotation // Annotated method to trigger pointcut for annotation

public void methodWithAnnotations() {

System.out.println("Method with annotations executed");

Name: Prajwal Dikshit 125 |


Page
Subject: Advanced Java Lab Code:MCAL12

MainApp.java

package com.example;

import org.springframework.context.ApplicationContext;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MainApp {

public static void main(String[] args) {

// Initialize Spring context

ApplicationContext context = new


AnnotationConfigApplicationContext(AppConfig.class);

// Get MyService bean

MyService myService = context.getBean(MyService.class);

// Test different methods

System.out.println("Calling greeting method:");

myService.greeting("Alice");

System.out.println("Calling farewell method:");

myService.farewell("Bob");

Name: Prajwal Dikshit 126 |


Page
Subject: Advanced Java Lab Code:MCAL12

System.out.println("Calling processMessage method:");

String processedMessage = myService.processMessage("Hello World");

System.out.println("Calling method with int argument:");

myService.methodWithArgs(25);

// Test method with annotation (you need to create the annotation first)

System.out.println("Calling method with annotation:");

myService.methodWithAnnotations();

Output:

Name: Prajwal Dikshit 127 |


Page
Subject: Advanced Java Lab Code:MCAL12

Practical 9 – Assignment based on Spring JDBC

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: Prajwal Dikshit 128 |


Page
Subject: Advanced Java Lab Code:MCAL12

Create a table in your database

CREATE TABLE employee(

id INT PRIMARY KEY,

name VARCHAR(100),

role VARCHAR(100) );

Pom.xml

<dependencies>

<!-- Spring Core -->

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-core</artifactId>

<version>5.3.10</version>

</dependency>

<!-- Spring Context -->

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-context</artifactId>

<version>5.3.10</version>

Name: Prajwal Dikshit 129 |


Page
Subject: Advanced Java Lab Code:MCAL12

</dependency>

<!-- Spring JDBC -->

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-jdbc</artifactId>

<version>5.3.10</version>

</dependency>

<!-- MySQL Connector -->

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<version>8.0.26</version>

</dependency>

<!-- Spring Test (Optional, for testing purposes) -->

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-test</artifactId>

<version>5.3.10</version>

<scope>test</scope>

</dependency>

<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->

<dependency>

<groupId>org.slf4j</groupId>

<artifactId>slf4j-api</artifactId>

<version>2.0.16</version>

</dependency>

Name: Prajwal Dikshit 130 |


Page
Subject: Advanced Java Lab Code:MCAL12

<!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic -->

<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

public interface EmployeeDAO {

//Create

public void save(Employee employee);

Name: Prajwal Dikshit 131 |


Page
Subject: Advanced Java Lab Code:MCAL12

//Read

public Employee getById(int id);

//Update

public void update(Employee employee);

//Delete

public void deleteById(int id);

//Get All

public List<Employee> getAll();

EmployeeDAOImpl.java

package com.journaldev.spring.jdbc.dao;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

Name: Prajwal Dikshit 132 |


Page
Subject: Advanced Java Lab Code:MCAL12

import java.sql.SQLException;

import java.util.ArrayList;

import java.util.List;

import javax.sql.DataSource;

import com.journaldev.spring.jdbc.model.Employee;

public class EmployeeDAOImpl implements EmployeeDAO {

private DataSource dataSource;

public void setDataSource(DataSource dataSource) {

this.dataSource = dataSource;

@Override

public void save(Employee employee) {

String query = "insert into Employee (id, name, role) values (?,?,?)";

Connection con = null;

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());

int out = ps.executeUpdate();

if (out != 0) {

System.out.println("Employee saved with id=" + employee.getId());

} else

System.out.println("Employee save failed withid=" + employee.getId());

} catch (SQLException e) {

e.printStackTrace();

Name: Prajwal Dikshit 133 |


Page
Subject: Advanced Java Lab Code:MCAL12

} finally {

try {

ps.close();

con.close();

} catch (SQLException e) {

e.printStackTrace();

@Override

public Employee getById(int id) {

String query = "select name, role from Employee where id = ?";

Employee emp = null;

Connection con = null;

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 = new Employee();

emp.setId(id);

emp.setName(rs.getString("name"));

emp.setRole(rs.getString("role"));

System.out.println("Employee Found::" + emp);

} else {

System.out.println("No Employee found with id=" + id);

Name: Prajwal Dikshit 134 |


Page
Subject: Advanced Java Lab Code:MCAL12

} catch (SQLException e) {

e.printStackTrace();

} finally {

try {

rs.close();

ps.close();

con.close();

} catch (SQLException e) {

e.printStackTrace();

return emp;

@Override

public void update(Employee employee) {

String query = "update Employee set name=?, role=? where id=?";

Connection con = null;

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());

int out = ps.executeUpdate();

if (out != 0) {

System.out.println("Employee updated withid=" + employee.getId());

} else

System.out.println("No Employee found withid=" + employee.getId());

} catch (SQLException e) {

Name: Prajwal Dikshit 135 |


Page
Subject: Advanced Java Lab Code:MCAL12

e.printStackTrace();

} finally {

try {

ps.close();

con.close();

} catch (SQLException e) {

e.printStackTrace();

@Override

public void deleteById(int id) {

String query = "delete from Employee where id=?";

Connection con = null;

PreparedStatement ps = null;

try {

con = dataSource.getConnection();

ps = con.prepareStatement(query);

ps.setInt(1, id);

int out = ps.executeUpdate();

if (out != 0) {

System.out.println("Employee deleted with id=" + id);

} else

System.out.println("No Employee found with id=" + id);

} catch (SQLException e) {

e.printStackTrace();

} finally {

try {

ps.close();

con.close();

Name: Prajwal Dikshit 136 |


Page
Subject: Advanced Java Lab Code:MCAL12

} catch (SQLException e) {

e.printStackTrace();

@Override

public List<Employee> getAll() {

String query = "select id, name, role from Employee";

List<Employee> empList = new ArrayList<Employee>();

Connection con = null;

PreparedStatement ps = null;

ResultSet rs = null;

try {

con = dataSource.getConnection();

ps = con.prepareStatement(query);

rs = ps.executeQuery();

while (rs.next()) {

Employee emp = new Employee();

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();

Name: Prajwal Dikshit 137 |


Page
Subject: Advanced Java Lab Code:MCAL12

} catch (SQLException e) {

e.printStackTrace();

return empList;

Name: Prajwal Dikshit 138 |


Page
Subject: Advanced Java Lab Code:MCAL12

Name: Prajwal Dikshit 139 |


Page
Subject: Advanced Java Lab Code:MCAL12

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;

public class EmployeeDAOJDBCTemplateImpl implements EmployeeDAO {

private DataSource dataSource;

public void setDataSource(DataSource dataSource) {

this.dataSource = dataSource;

Name: Prajwal Dikshit 140 |


Page
Subject: Advanced Java Lab Code:MCAL12

@Override

public void save(Employee employee) {

String query = "insert into Employee (id, name, role) values (?,?,?)";

JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

Object[] args = new Object[] { employee.getId(), employee.getName(), employee.getRole() };

int out = jdbcTemplate.update(query, args);

if (out != 0) {

System.out.println("Employee saved with id=" + employee.getId());

} else

System.out.println("Employee save failed with id=" + employee.getId());

@Override

public Employee getById(int id) {

String query = "select id, name, role from Employee where id = ?";

JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

//using RowMapper anonymous class, we can create a separate RowMapper for reuse

Employee emp = jdbcTemplate.queryForObject(query, new Object[] { id }, new


RowMapper<Employee>() {

@Override

public Employee mapRow(ResultSet rs, int rowNum) throws SQLException {

Employee emp = new Employee();

emp.setId(rs.getInt("id"));

emp.setName(rs.getString("name"));

emp.setRole(rs.getString("role"));

return emp;

});

return emp;

Name: Prajwal Dikshit 141 |


Page
Subject: Advanced Java Lab Code:MCAL12

@Override

public void update(Employee employee) {

String query = "update Employee set name=?, role=? where id=?";

JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

Object[] args = new Object[] { employee.getName(), employee.getRole(), employee.getId() };

int out = jdbcTemplate.update(query, args);

if (out != 0) {

System.out.println("Employee updated with id=" + employee.getId());

} else

System.out.println("No Employee found withid=" + employee.getId());

@Override

public void deleteById(int id) {

String query = "delete from Employee where id=?";

JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

int out = jdbcTemplate.update(query, id);

if (out != 0) {

System.out.println("Employee deleted with id=" + id);

} else

System.out.println("No Employee found with id=" + id);

@Override

public List<Employee> getAll() {

String query = "select id, name, role from Employee";

JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

List<Employee> empList = new ArrayList<Employee>();

List<Map<String, Object>> empRows = jdbcTemplate.queryForList(query);

Name: Prajwal Dikshit 142 |


Page
Subject: Advanced Java Lab Code:MCAL12

for (Map<String, Object> empRow : empRows) {

Employee emp = new Employee();

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;

Name: Prajwal Dikshit 143 |


Page
Subject: Advanced Java Lab Code:MCAL12

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;

public class SpringMain {

public static void main(String[] args) {

Scanner sc1 = new Scanner(System.in);

//Get the Spring Context

ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");

//Get the EmployeeDAO Bean

//EmployeeDAO employeeDAO = ctx.getBean("employeeDAO",EmployeeDAO.class);

//To use JdbcTemplate

EmployeeDAO employeeDAO = ctx.getBean("employeeDAOJDBCTemplate", EmployeeDAO.class);

System.out.println("Enter 1 to start and 0 to end");

int run = sc1.nextInt();

while (run != 0) {

Name: Prajwal Dikshit 144 |


Page
Subject: Advanced Java Lab Code:MCAL12

System.out.println("CRUD OPERATIONS USING JDBC SPRING");

System.out.println("Select one of the options");

System.out.println("1: Add data");

System.out.println("2: Read data");

System.out.println("3: Update data");

System.out.println("4: Delete data");

System.out.println("5: Display all data");

System.out.println("Enter the choice");

int choice = sc1.nextInt();

Employee emp = new Employee();

switch (choice) {

case 1:

System.out.println("Enter id");

int num = sc1.nextInt();

System.out.println("Enter the name");

String name = sc1.next();

System.out.println("Enter the job role");

String job = sc1.next();

emp.setId(num);

emp.setName(name);

emp.setRole(job);

//Create

employeeDAO.save(emp);

System.out.println("Added to database");

break;

case 2:

System.out.println("Enter the id to read");

int id = sc1.nextInt();

Employee emp1 = employeeDAO.getById(id);

System.out.println("Employee Retrieved::" + emp1);

break;

Name: Prajwal Dikshit 145 |


Page
Subject: Advanced Java Lab Code:MCAL12

case 3:

//Update

emp.setRole("CEO");

employeeDAO.update(emp);

break;

case 4:

System.out.println("Enter the id to delete");

int delid = sc1.nextInt();

employeeDAO.deleteById(delid);

break;

case 5:

List<Employee> empList = employeeDAO.getAll();

System.out.println(empList);

break;

System.out.println("Exited program with 0");

ctx.close();

Name: Prajwal Dikshit 146 |


Page
Subject: Advanced Java Lab Code:MCAL12

Employee.java

package com.journaldev.spring.jdbc.model;

public class Employee {

private int id;

private String name;

private String role;

public int getId() {

return id;

public void setId(int id) {

this.id = id;

public String getName() {

return name;

Name: Prajwal Dikshit 147 |


Page
Subject: Advanced Java Lab Code:MCAL12

public void setName(String name) {

this.name = name;

public String getRole() {

return role;

public void setRole(String role) {

this.role = role;

@Override

public String toString() {

return "{ID=" + id + ",Name=" + name + ",Role=" + role + "}";

Spring.xml

Name: Prajwal Dikshit 148 |


Page
Subject: Advanced Java Lab Code:MCAL12

<?xml version="1.0" encoding="UTF-8"?>

<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">

<property name="dataSource" ref="dataSource" />

</bean>

<bean id="employeeDAOJDBCTemplate"

class="com.journaldev.spring.jdbc.dao.EmployeeDAOJDBCTemplateImpl">

<property name="dataSource" ref="dataSource" />

</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" />

<property name="username" value="root" />

<property name="password" value="root" />

</bean>

</beans>

Name: Prajwal Dikshit 149 |


Page
Subject: Advanced Java Lab Code:MCAL12

Output:

Name: Prajwal Dikshit 150 |


Page
Subject: Advanced Java Lab Code:MCAL12

Practical 9.2

Aim: Write a program to demonstrate PreparedStatements in Spring JDBCTemplate.

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.

 Creating a Prepared Statement:

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.

 Executing the Statement:

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

CREATE DATABASE Nikhil;

USE Nikhil;

CREATE TABLE employee (

Name: Prajwal Dikshit 151 |


Page
Subject: Advanced Java Lab Code:MCAL12

id INT AUTO_INCREMENT PRIMARY KEY,

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>

<!-- Spring JDBC -->

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-jdbc</artifactId>

<version>5.3.10</version>

</dependency>

<!-- MySQL Connector -->

Name: Prajwal Dikshit 152 |


Page
Subject: Advanced Java Lab Code:MCAL12

<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;

Name: Prajwal Dikshit 153 |


Page
Subject: Advanced Java Lab Code:MCAL12

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")

public class SpringJdbcConfig {

@Bean

public DataSource dataSource() {

DriverManagerDataSource dataSource = new DriverManagerDataSource();

dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");

dataSource.setUrl("jdbc:mysql://localhost:3306/Nikhil;

dataSource.setUsername("root");

dataSource.setPassword("root");

return dataSource;

@Bean

public JdbcTemplate jdbcTemplate(DataSource dataSource) {

return new JdbcTemplate(dataSource);

Name: Prajwal Dikshit 154 |


Page
Subject: Advanced Java Lab Code:MCAL12

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

public class EmployeeDAO {

@Autowired

private JdbcTemplate jdbcTemplate;

public void insertEmployee(int id, String name, String department) {

String sql = "INSERT INTO employee (id, name, department) VALUES (?, ?, ?)";

jdbcTemplate.update(connection -> {

PreparedStatement ps = connection.prepareStatement(sql);

Name: Prajwal Dikshit 155 |


Page
Subject: Advanced Java Lab Code:MCAL12

ps.setInt(1, id);

ps.setString(2, name);

ps.setString(3, department);

return ps;

});

public void updateEmployee(int id, String name, String department) {

String sql = "UPDATE employee SET name = ?, department = ? WHERE id = ?";

jdbcTemplate.update(connection -> {

PreparedStatement ps = connection.prepareStatement(sql);

ps.setString(1, name);

ps.setString(2, department);

ps.setInt(3, id);

return ps;

});

public void deleteEmployee(int id) {

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

jdbcTemplate.update(connection -> {

PreparedStatement ps = connection.prepareStatement(sql);

ps.setInt(1, id);

return ps;

});

Name: Prajwal Dikshit 156 |


Page
Subject: Advanced Java Lab Code:MCAL12

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;

public class MainApp {

public static void main(String[] args) {

ApplicationContext context = new


AnnotationConfigApplicationContext(SpringJdbcConfig.class);

EmployeeDAO employeeDAO = context.getBean(EmployeeDAO.class);

// Insert a new employee

employeeDAO.insertEmployee(1, "John Doe", "Engineering");

Name: Prajwal Dikshit 157 |


Page
Subject: Advanced Java Lab Code:MCAL12

System.out.println("Operations completed successfully.");

Output:

Practical 9.3

Aim: Write a program in spring JDBC to demonstrate ResultSetExtractor Interface.

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.

Name: Prajwal Dikshit 158 |


Page
Subject: Advanced Java Lab Code:MCAL12

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>

<version>8.0.28</version> <!-- Or any other version depending on your DB -->

</dependency>

</dependencies>

Create a Database

Name: Prajwal Dikshit 159 |


Page
Subject: Advanced Java Lab Code:MCAL12

Create Database StudentsDB;

Use StudentsDB;

CREATE TABLE student (

id INT PRIMARY KEY,

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;

public class Student {

private int id;

private String name;

private int age;

// Constructors, getters, setters, toString()

public Student(int id, String name, int age) {

this.id = id;

this.name = name;

this.age = age;

public int getId() {

return id;

Name: Prajwal Dikshit 160 |


Page
Subject: Advanced Java Lab Code:MCAL12

public void setId(int id) {

this.id = id;

public String getName() {

return name;

public void setName(String name) {

this.name = name;

public int getAge() {

return age;

public void setAge(int age) {

this.age = age;

@Override

public String toString() {

return "Student{id=" + id + ", name='" + name + "', age=" + age + '}';

Name: Prajwal Dikshit 161 |


Page
Subject: Advanced Java Lab Code:MCAL12

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;

public class StudentResultSetExtractor implements ResultSetExtractor<List<Student>> {

@Override

public List<Student> extractData(ResultSet rs) throws SQLException {

List<Student> students = new ArrayList<>();

while (rs.next()) {

int id = rs.getInt("id");

String name = rs.getString("name");

Name: Prajwal Dikshit 162 |


Page
Subject: Advanced Java Lab Code:MCAL12

int age = rs.getInt("age");

students.add(new Student(id, name, age));

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;

public class StudentService {

private JdbcTemplate jdbcTemplate;

// Constructor injection for JdbcTemplate

public StudentService(DataSource dataSource) {

this.jdbcTemplate = new JdbcTemplate(dataSource);

Name: Prajwal Dikshit 163 |


Page
Subject: Advanced Java Lab Code:MCAL12

public List<Student> getAllStudents() {

String sql = "SELECT id, name, age FROM student";

// Use ResultSetExtractor to extract data

return jdbcTemplate.query(sql, new StudentResultSetExtractor());

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;

public class Main {

public static void main(String[] args) {

// Set up the data source

DriverManagerDataSource dataSource = new DriverManagerDataSource();

dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");

dataSource.setUrl("jdbc:mysql://localhost:3306/StudentsDB");

Name: Prajwal Dikshit 164 |


Page
Subject: Advanced Java Lab Code:MCAL12

dataSource.setUsername("root");

dataSource.setPassword("root");

// Initialize Spring context and student service

ApplicationContext context = new AnnotationConfigApplicationContext();

StudentService studentService = new StudentService(dataSource);

// Get all students and print them

List<Student> students = studentService.getAllStudents();

students.forEach(System.out::println);

Right click on project and Run as Java Application

Output:

Practical 9.4

Aim: Write a program to demonstrate RowMapper interface to fetch the records from the
database.

Name: Prajwal Dikshit 165 |


Page
Subject: Advanced Java Lab Code:MCAL12

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 database Students;

CREATE TABLE User ( id INT PRIMARY KEY, name VARCHAR(100), email VARCHAR(100) );

insert into User values (8, “Tejas”, “[email protected]”);

pom.xml

<dependencies>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-core</artifactId>

<version>6.1.14</version>

</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-context</artifactId>

<version>6.1.14</version>

</dependency>

<!-- Spring JDBC -->

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-jdbc</artifactId>

<version>5.3.10</version> <!-- Or the latest version -->

</dependency>

Name: Prajwal Dikshit 166 |


Page
Subject: Advanced Java Lab Code:MCAL12

<!-- MySQL Connector (or your respective database driver) -->

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<version>8.0.26</version> <!-- Or the latest version -->

</dependency>

</dependencies>

Main.java

package com.example;

import java.util.List; // Importing List from java.util

public class Main {

public static void main(String[] args) {

// Create an instance of UserDao to interact with the database

UserDao userDao = new UserDao();

// Fetch all users from the database

List<User> users = userDao.getAllUsers();

// Print each user to the console

Name: Prajwal Dikshit 167 |


Page
Subject: Advanced Java Lab Code:MCAL12

for (User user : users) {

System.out.println(user);

User.java

package com.example;

public class User {

private int id;

private String name;

private String email;

// Constructor

public User(int id, String name, String email) {

this.id = id;

this.name = name;

this.email = email;

Name: Prajwal Dikshit 168 |


Page
Subject: Advanced Java Lab Code:MCAL12

// Getters and setters

public int getId() {

return id;

public void setId(int id) {

this.id = id;

public String getName() {

return name;

public void setName(String name) {

this.name = name;

public String getEmail() {

return email;

public void setEmail(String email) {

this.email = email;

@Override

public String toString() {

return "User{id=" + id + ", name='" + name + "', email='" + email + "'}";

Name: Prajwal Dikshit 169 |


Page
Subject: Advanced Java Lab Code:MCAL12

UserDao.java

package com.example;

import org.springframework.jdbc.core.JdbcTemplate;

import org.springframework.jdbc.datasource.DriverManagerDataSource;

import java.util.List;

public class UserDao {

private JdbcTemplate jdbcTemplate;

public UserDao() {

// Set up the data source (for MySQL in this case)

DriverManagerDataSource dataSource = new DriverManagerDataSource();

dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");

dataSource.setUrl("jdbc:mysql://localhost:3306/tejas_mca"); // Update with your DB details

dataSource.setUsername("root"); // Update with your DB username

dataSource.setPassword("root"); // Update with your DB password

Name: Prajwal Dikshit 170 |


Page
Subject: Advanced Java Lab Code:MCAL12

// Initialize the JdbcTemplate with the data source

jdbcTemplate = new JdbcTemplate(dataSource);

// Method to fetch all users from the database

public List<User> getAllUsers() {

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

return jdbcTemplate.query(sql, new UserRowMapper());

UserRowMapper.java

package com.example;

import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;

Name: Prajwal Dikshit 171 |


Page
Subject: Advanced Java Lab Code:MCAL12

import java.sql.SQLException;

public class UserRowMapper implements RowMapper<User> {

@Override

public User mapRow(ResultSet rs, int rowNum) throws SQLException {

int id = rs.getInt("id");

String name = rs.getString("name");

String email = rs.getString("email");

// Create a User object and return it

return new User(id, name, email);

Output:

Name: Prajwal Dikshit 172 |


Page
Subject: Advanced Java Lab Code:MCAL12

Practical 10 - Assignment based Spring Boot and RESTful Web Services

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

public class MessageController {

@GetMapping("/") // Maps to http://localhost:8081/

public String showDefaultMessage() {

return "Write a program to create a Simple spring Boot application that prints a message:= "+
"Hii Welcome to Spring Boot application";

Name: Prajwal Dikshit 173 |


Page
Subject: Advanced Java Lab Code:MCAL12

SimpleSpringAppApplication.java

package com.springboot.restful.app;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class SimpleSpringAppApplication {

public static void main(String[] args) {

// Launch Spring Boot application

SpringApplication.run(SimpleSpringAppApplication.class, args);

// Print a message

System.out.println("Write a program to create a Simple spring Boot application that prints a


message:= "+

"Hii Welcome to Spring Boot application");

Name: Prajwal Dikshit 174 |


Page
Subject: Advanced Java Lab Code:MCAL12

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:

Set Up a Spring Boot Project

1. Open Spring Tool Suite (STS) in Eclipse.

2. Go to File > New > Spring Starter Project.

3. Fill in the following fields:

o Project Name: restful-webservice

o Packaging: Jar

o Type: Maven

o Java Version: 21

o Language: Java

o Artifact: com.springboot.app

Name: Prajwal Dikshit 175 |


Page
Subject: Advanced Java Lab Code:MCAL12

o Package name: com.springboot.restful.app

Click Next

o Dependencies: Choose Spring Web, Spring Boot DevTools

o Spring Version: 3.3.6

File Structure

Product.java

package com.springboot.restful.app;

public class Product {

private int id;

private String name;

private double price;

// Getters and setters

public int getId() {

return id;

public void setId(int id) {

this.id = id;

Name: Prajwal Dikshit 176 |


Page
Subject: Advanced Java Lab Code:MCAL12

public String getName() {

return name;

public void setName(String name) {

this.name = name;

public double getPrice() {

return price;

public void setPrice(double price) {

this.price = price;

Name: Prajwal Dikshit 177 |


Page
Subject: Advanced Java Lab Code:MCAL12

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")

public class ProductController {

// In-memory list to simulate a database

private List<Product> products = new ArrayList<>();

Name: Prajwal Dikshit 178 |


Page
Subject: Advanced Java Lab Code:MCAL12

// GET method for retrieving all products

@GetMapping

public List<Product> getAllProducts() {

return products;

// GET method for retrieving a product by its ID

@GetMapping("/{id}")

public Product getProductById(@PathVariable int id) {


return products.stream().filter(product -> product.getId() ==
id).findFirst().orElse(null);

// POST method for creating a new product

@PostMapping

public Product createProduct(@RequestBody Product product) {

products.add(product);

return product;

// PUT method for updating an existing product

@PutMapping("/{id}")

public Product updateProduct(@PathVariable int id, @RequestBody Product product) {

Product existingProduct = products.stream().filter(p -> p.getId() ==


id).findFirst().orElse(null);

if (existingProduct != null) {

existingProduct.setName(product.getName());

existingProduct.setPrice(product.getPrice());

return existingProduct;

Name: Prajwal Dikshit 179 |


Page
Subject: Advanced Java Lab Code:MCAL12

// PATCH method for partially updating a product

@PatchMapping("/{id}")

public Product partialUpdateProduct(@PathVariable int id, @RequestBody Product product)


{

Product existingProduct = products.stream().filter(p -> p.getId() ==


id).findFirst().orElse(null);

if (existingProduct != null) {

if (product.getName() != null) {

existingProduct.setName(product.getName());

if (product.getPrice() != 0) {

existingProduct.setPrice(product.getPrice());

return existingProduct;

// DELETE method for deleting a product by its ID

@DeleteMapping("/{id}")

public String deleteProduct(@PathVariable int id) {

Product product = products.stream().filter(p -> p.getId() == id).findFirst().orElse(null);

if (product != null) {

products.remove(product);

return "Product deleted successfully!";

return "Product not found!";

Name: Prajwal Dikshit 180 |


Page
Subject: Advanced Java Lab Code:MCAL12

Output:

Insert product

Name: Prajwal Dikshit 181 |


Page
Subject: Advanced Java Lab Code:MCAL12

Delete product

Practical 10.3

Aim: Write a program to demonstrate Database Connection with spring boot.

Code:

Name: Prajwal Dikshit 182 |


Page
Subject: Advanced Java Lab Code:MCAL12

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;

Name: Prajwal Dikshit 183 |


Page
Subject: Advanced Java Lab Code:MCAL12

@Entity

public class Employee {

@Id

private Long id;

private String name;

private String email;

// Default constructor

public Employee() {

// Constructor with parameters

public Employee(Long id, String name, String email) {

this.id = id;

this.name = name;

this.email = email;

// Getters and setters

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 getEmail() {

return email;

Name: Prajwal Dikshit 184 |


Page
Subject: Advanced Java Lab Code:MCAL12

public void setEmail(String 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")

public class EmployeeController {

@Autowired

Name: Prajwal Dikshit 185 |


Page
Subject: Advanced Java Lab Code:MCAL12

private EmployeeRepository employeeRepository;

@GetMapping

public List<Employee> getAllEmployees() {

return employeeRepository.findAll();

@PostMapping

public Employee createEmployee(@RequestBody Employee employee) {

return employeeRepository.save(employee);

@GetMapping("/{id}")

public Employee getEmployeeById(@PathVariable Long 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;

public interface EmployeeRepository extends JpaRepository<Employee, Long> {

// No need for implementation, Spring Data JPA handles it

Name: Prajwal Dikshit 186 |


Page
Subject: Advanced Java Lab Code:MCAL12

SpringBootDatabaseApplication.java

package com.springbootdb.restful.app;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class SpringBootDatabaseApplication {

public static void main(String[] args) {

SpringApplication.run(SpringBootDatabaseApplication.class, args);

To test the endpoints:

Open Git Bash and run following command to test various HTTP methods:

# 1. POST (Create) a new employee

curl -X POST http://localhost:8080/api/employees \

-H "Content-Type: application/json" \

-d '{"id": 1, "name": "Nikhil Naik", "email":[email protected]}'

{"id":2,"name":"Aachal Shah","email":"[email protected]"}

curl -X POST http://localhost:8080/api/employees \

-H "Content-Type: application/json" \

Name: Prajwal Dikshit 187 |


Page
Subject: Advanced Java Lab Code:MCAL12

-d ' {"id": 1, "name": "Nikhil Naik", "email": "[email protected]"}'

{"id":2,"name":"Aachal Shah","email":"[email protected]"}

Output:

Name: Prajwal Dikshit 188 |


Page

You might also like