Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

AJP PRACT Ap

Download as pdf or txt
Download as pdf or txt
You are on page 1of 53

EXPERIMENT NO: 1

EXERCISE:

1. Write a program to display IP address of local machine.


import java.net.InetAddress; public
class IP_Address
{ public static void main(String args[]) throws Exception
{
InetAddress IP = InetAddress.getLocalHost();
System.out.println("IP of my system is := "+IP.getHostAddress());
}
}

2. Write a program to displaying source code of a webpage by URLConnecton class

also display length of it.

import java.io.*;

public class SourceCodeViewer {

public static void main(String[] args) {

String filePath = "C:/Users/windows 10/Desktop/java program/hello world.html"; try

FileInputStream fis = new FileInputStream(filePath);

BufferedReader reader = new BufferedReader(new InputStreamReader(fis));


String line;
int length = 0; while ((line =

reader.readLine()) != null) {

System.out.println(line);

length += line.length();

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
System.out.println("\nLength of source code: " + length); reader.close();

} catch (FileNotFoundException e) {
System.out.println("File not found: " + filePath);
} catch (IOException e) {

System.out.println("Error reading from file: " + e.getMessage());

3. Write a program to display the expiration date and last modified date for the following

URL http://www.sal.edu.in
import java.io.IOException;

import java.net.URL; import

java.net.URLConnection;

import java.util.Date;

public class URLInfoViewer {

public static void main(String[] args) {


String urlString = "http://www.sal.edu.in";

try {

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
URL url = new URL(null, urlString);
URLConnection connection = url.openConnection();
// Get expiration date
long expiration = connection.getExpiration();
Date expirationDate = new Date(expiration);
System.out.println("Expiration Date: " + expirationDate);

// Get last modified date

long lastModified = connection.getLastModified();


Date lastModifiedDate = new Date(lastModified);
System.out.println("Last Modified Date: " + lastModifiedDate);

} catch (IOException e) {

System.out.println("Error fetching URL information: " + e.getMessage());


}
}
}

QUIZ:

1. What is URL Class? Explain Use of it?

The `URL` class in Java is used to represent and manipulate Uniform Resource Locators (URLs). It
provides a way to work with web addresses and perform operations like opening connections,
downloading files, parsing URLs, and constructing URLs. It facilitates tasks involving network
communication and resource manipulation on the web.

2. What is URL Connection Class? Explain Use of it?

The `URLConnection` class in Java is used to establish a connection to a resource specified by a URL
and perform various operations on that resource. It provides methods for sending HTTP requests,
retrieving response codes and headers, reading the content of the resource, handling cookies, and more.
It allows you to interact with remote resources like web pages, APIs, or files and perform tasks like data
retrieval, submission, and manipulation over a network connection.

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
NAME- SAIYED MOHAMMADSADAB
ENROLMENT: 211260107010
EXPERIMENT NO: 2

EXERCISE:

1. Write a TCP or UDP client and server Program.

File: MyServer.java

import java.io.*; import

java.net.*;

public class MyServer {

public static void main(String[] args){ try{

ServerSocket ss=new ServerSocket(6666);

Socket s=ss.accept();//establishes connection

DataInputStream dis=new DataInputStream(s.getInputStream());

String str=(String)dis.readUTF();

System.out.println("message=

"+str); ss.close();

}catch(Exception e){System.out.println(e);}

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
}

File: MyClient.java

import java.io.*; import java.net.*;

public class MyClient { public static

void main(String[] args) { try{

Socket s=new Socket("localhost",6666);


DataOutputStream dout=new DataOutputStream(s.getOutputStream()); dout.writeUTF("Hello

Server");

dout.flush();
dout.close();

s.close();

}catch(Exception e){System.out.println(e);}

2. Write a client-server program using TCP or UDP where the client sends 10 numbers

and server responds with the numbers in sorted order.

Server:

import java.io.*;

import java.net.*;

import

java.util.Arrays;

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
public class TCPServer {

public static void main(String[] args) { try

ServerSocket serverSocket = new ServerSocket(12345);


System.out.println("Server waiting for client...");
Socket socket = serverSocket.accept();
System.out.println("Client connected.");

BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

// Receive numbers from client


String numbersStr = in.readLine();
String[] numbersArray = numbersStr.split(",");

int[] numbers = new int[numbersArray.length];

for (int i = 0; i < numbersArray.length; i++) {

numbers[i] = Integer.parseInt(numbersArray[i]);

// Sort numbers
Arrays.sort(numbers);

// Send sorted numbers back to client

StringBuilder sortedNumbersStr = new StringBuilder(); for

(int number : numbers) {

sortedNumbersStr.append(number).append(",");

out.println(sortedNumbersStr);

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
// Close connections

socket.close();

serverSocket.close();

} catch (IOException e) {
e.printStackTrace();
}

Client:

import java.io.*; import

java.net.*;

public class TCPClient {

public static void main(String[] args) { try

Socket socket = new Socket("localhost", 12345);

BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));


PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

// Send numbers to server

System.out.println("Enter 10 numbers separated by commas:");

String numbersStr = userInput.readLine();

out.println(numbersStr);

// Receive sorted numbers from server


String sortedNumbersStr = in.readLine();
System.out.println("Sorted numbers received from server: " + sortedNumbersStr);
// Close connections

socket.close();

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
} catch (IOException e) {
e.printStackTrace();
}

3. Write a UDP Client-Server program in which the Client sends any string and Server

responds with Reverse string.

Server:

import java.net.*;

public class UDPServer {

public static void main(String[] args) { try

DatagramSocket serverSocket = new DatagramSocket(9876);

byte[] receiveData = new byte[1024]; byte[]

sendData = new byte[1024];

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

serverSocket.receive(receivePacket);

String sentence = new String(receivePacket.getData(), 0, receivePacket.getLength());

System.out.println("Received from client: " + sentence);

InetAddress IPAddress = receivePacket.getAddress(); int

port = receivePacket.getPort();

String reverseSentence = new StringBuilder(sentence).reverse().toString(); sendData

= reverseSentence.getBytes();

DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);

serverSocket.send(sendPacket);

} catch (Exception e) {
e.printStackTrace();
}

Client:

import java.net.*;

public class UDPClient {

public static void main(String[] args) { try

DatagramSocket clientSocket = new DatagramSocket();


InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData;

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
byte[] receiveData = new byte[1024];

String sentence = "Hello UDP Server"; sendData

= sentence.getBytes();

DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);

clientSocket.send(sendPacket);

DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

clientSocket.receive(receivePacket);

String modifiedSentence = new String(receivePacket.getData(), 0, receivePacket.getLength());

System.out.println("From Server: " + modifiedSentence);

clientSocket.close();

} catch (Exception e) {
e.printStackTrace();
}

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
4. Write a TCP Client-Server program to get the Date &amp; Time details from Server on the

Client request.

Server:

import java.io.*;

import java.net.*;

import

java.util.Date;

public class TCPServerDateTime { public

static void main(String[] args) {

try {

ServerSocket serverSocket = new ServerSocket(12345);


System.out.println("Server waiting for client...");

while (true) {

Socket socket = serverSocket.accept();


System.out.println("Client connected.");

PrintWriter out = new PrintWriter(socket.getOutputStream(), true);


out.println(new Date().toString());
socket.close();
System.out.println("Connection closed.");
}

} catch (IOException e) {
e.printStackTrace();
}

Client:

import java.io.*; import

java.net.*;

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
public class TCPClientDateTime { public

static void main(String[] args) {

try {

Socket socket = new Socket("localhost", 12345);

BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); String

dateTime = in.readLine();

System.out.println("Date & Time received from server: " + dateTime);

socket.close();

} catch (IOException e) {
e.printStackTrace();
}

5. Write a client server program using TCP where client sends a string and server checks

whether that string is palindrome or not and responds with appropriate message.

Server:

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
import java.io.*; import

java.net.*;

public class TCPServerPalindrome { public

static void main(String[] args) {

try {

ServerSocket serverSocket = new ServerSocket(12345);


System.out.println("Server waiting for client...");

while (true) {

Socket socket = serverSocket.accept();


System.out.println("Client connected.");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

String str = in.readLine();


boolean isPalindrome = isPalindrome(str);

if (isPalindrome) {
out.println("The string \"" + str + "\" is a palindrome.");

} else {
out.println("The string \"" + str + "\" is not a palindrome.");

socket.close();
System.out.println("Connection closed.");
}

} catch (IOException e) {
e.printStackTrace();
}

private static boolean isPalindrome(String str) { int

left = 0;

int right = str.length() - 1;

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
while (left < right) {
if (str.charAt(left) != str.charAt(right)) { return

false;

left++; right--

return true;

}}

Client:

import java.io.*; import

java.net.*;

public class TCPClientPalindrome { public

static void main(String[] args) {

try {

Socket socket = new Socket("localhost", 12345);

BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));


PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

System.out.println("Enter a string:");

String str = userInput.readLine();

out.println(str);

String response = in.readLine();


System.out.println("Response from server: " + response);
socket.close();
} catch (IOException e) {

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
e.printStackTrace();
}

6. Write a client-server program using UDP socket. Client send list of N numbers to

server and server respond the sum of N numbers.

Server:

import java.net.*;

public class UDPServerSum {

public static void main(String[] args) { try

DatagramSocket serverSocket = new DatagramSocket(9876);


byte[] receiveData = new byte[1024]; byte[]

sendData = new byte[1024];

while (true) {

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

serverSocket.receive(receivePacket);

String numbersStr = new String(receivePacket.getData(), 0, receivePacket.getLength()); String[]

numbersArray = numbersStr.split(",");

int sum = 0;

for (String numStr : numbersArray) {

int num = Integer.parseInt(numStr);

sum += num;

InetAddress clientIPAddress = receivePacket.getAddress(); int

clientPort = receivePacket.getPort();

String sumStr = Integer.toString(sum); sendData

= sumStr.getBytes();

DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, clientIPAddress,


clientPort);
serverSocket.send(sendPacket);

} catch (Exception e) {
e.printStackTrace();
}

Client:

import java.net.*;

public class UDPClientSum {

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
public static void main(String[] args) { try

DatagramSocket clientSocket = new DatagramSocket();

InetAddress serverIPAddress = InetAddress.getByName("localhost");

byte[] sendData;

byte[] receiveData = new byte[1024];

String numbersStr = "10,20,30,40,50"; // Example list of numbers sendData

= numbersStr.getBytes();

DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverIPAddress, 9876);

clientSocket.send(sendPacket);

DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

clientSocket.receive(receivePacket);

String sumStr = new String(receivePacket.getData(), 0, receivePacket.getLength());

System.out.println("Sum received from server: " + sumStr);

clientSocket.close();
} catch (Exception e) {
e.printStackTrace();
}}}

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
7. Write a client-server program using UDP socket. Client send the list of N strings and

server responds the concatenation of those strings.

Server:

import java.net.*;

public class UDPServerConcatenate { public

static void main(String[] args) {

try {

DatagramSocket serverSocket = new DatagramSocket(9876);

byte[] receiveData = new byte[1024]; byte[]

sendData = new byte[1024];

while (true) {

DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

serverSocket.receive(receivePacket);

String[] stringsArray = new String(receivePacket.getData(), 0, receivePacket.getLength()).split(",");

StringBuilder concatenatedStrings = new StringBuilder(); for (String str : stringsArray) {

concatenatedStrings.append(str);

InetAddress clientIPAddress = receivePacket.getAddress(); int

clientPort = receivePacket.getPort();

sendData = concatenatedStrings.toString().getBytes();

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, clientIPAddress,
clientPort);
serverSocket.send(sendPacket);

} catch (Exception e) {
e.printStackTrace();
}

Client:

import java.net.*;

public class UDPClientConcatenate { public

static void main(String[] args) {

try {

DatagramSocket clientSocket = new DatagramSocket();

InetAddress serverIPAddress = InetAddress.getByName("localhost");


byte[] sendData;

byte[] receiveData = new byte[1024];

String[] stringsArray = {"Hello", " ", "World"}; // Example list of strings

StringBuilder stringsBuilder = new StringBuilder(); for (String str :

stringsArray) { stringsBuilder.append(str).append(",");

String concatenatedStrings = stringsBuilder.toString(); sendData

= concatenatedStrings.getBytes();

DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverIPAddress, 9876);

clientSocket.send(sendPacket);

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

clientSocket.receive(receivePacket);

String concatenatedResult = new String(receivePacket.getData(), 0, receivePacket.getLength());


System.out.println("Concatenated strings received from server: " + concatenatedResult);

clientSocket.close();

} catch (Exception e) {
e.printStackTrace();
}

QUIZ:

1. Differentiate the followings:

(I) TCP vs UDP

TCP:

1. Connection-oriented protocol.

2. Reliable delivery of data.

3. Ordered transmission of packets.

4. Provides error detection and retransmission mechanisms.

5. Higher packet overhead.

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
6. Slower compared to UDP.

7. Suitable for applications requiring guaranteed delivery and ordered data transmission, such as web browsing,
email, and file transfer.

UDP:

1. Connectionless protocol.

2. Unreliable delivery of data.

3. No guarantee of packet order.

4. No built-in error detection or retransmission.

5. Lower packet overhead.


6. Faster compared to TCP.

7. Suitable for real-time applications, multimedia streaming, online gaming, and situations where minimal delay
is more important than reliability.

(II) Socket Class vs Datagram Class

Socket class:

1. Works with TCP (Transmission Control Protocol).

2. Provides a reliable, connection-oriented, stream-based communication.

3. Establishes a connection between a client and a server.

4. Supports bidirectional communication between the client and the server.

Datagram class:

1. Works with UDP (User Datagram Protocol).

2. Provides a connectionless, unreliable, and message-based communication.

3. Does not establish a connection between the sender and receiver.

4. Supports unidirectional communication where the sender sends packets to one or more recipients.

2. What is Server Socket?

A server socket is a programming construct or object that allows a computer program to listen for
incoming network connections from clients. It provides a way for a program to act as a server and
accept connections from other programs or devices. The server socket waits for client requests and
establishes a connection with the client when a request is received, enabling communication
between the server and client over a network.

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
EXPERIMENT NO: 3
EXERCISE:

1. Write a program to insert,update,delete and print first five topper student from student

records in database using prepared statement.

package java1; import


java.sql.*;
public class StudentRecords { public static
void main(String args[]) { try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/Students", "root", "2374");

// Inserting records
insertStudent(con, "Alice", 95);
insertStudent(con, "Bob", 90);
insertStudent(con, "Charlie", 85);
insertStudent(con, "David", 80);
insertStudent(con, "Eve", 75);
// Updating records
updateStudentScore(con, "Bob", 92);

// Deleting a record
deleteStudent(con, "Eve");

// Printing first five topper students


printTopperStudents(con, 5);
con.close();
} catch (Exception e) { System.out.println(e);
}
}
private static void insertStudent(Connection con, String name, int score)
throws SQLException {
String sql = "INSERT INTO students (name, score) VALUES (?, ?)"; try
(PreparedStatement preparedStatement = con.prepareStatement(sql)) {
preparedStatement.setString(1, name); preparedStatement.setInt(2,
score); preparedStatement.executeUpdate();
System.out.println("Inserted record for " + name); }
}
private static void updateStudentScore(Connection con, String name, int
newScore) throws SQLException {
String sql = "UPDATE students SET score = ? WHERE name = ?";
try (PreparedStatement preparedStatement = con.prepareStatement(sql)) {
preparedStatement.setInt(1, newScore);
preparedStatement.setString(2, name);
int rowsAffected = preparedStatement.executeUpdate();
if (rowsAffected > 0) {
System.out.println("Updated score for " + name);
} else {
System.out.println("No record found for " + name); }
}
}
private static void deleteStudent(Connection con, String name) throws
SQLException {
String sql = "DELETE FROM students WHERE name = ?";

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
try (PreparedStatement preparedStatement = con.prepareStatement(sql)) {
preparedStatement.setString(1, name);
int rowsAffected = preparedStatement.executeUpdate();
if (rowsAffected > 0) {
System.out.println("Deleted record for " + name);
} else {
System.out.println("No record found for " + name); }
}
}
private static void printTopperStudents(Connection con, int limit) throws
SQLException {
String sql = "SELECT name, score FROM students ORDER BY score DESC LIMIT
?"; try (PreparedStatement preparedStatement = con.prepareStatement(sql)) {
preparedStatement.setInt(1, limit);
try (ResultSet resultSet = preparedStatement.executeQuery()) {
System.out.println("Topper students:"); while
(resultSet.next()) {
String name = resultSet.getString("name");
int score = resultSet.getInt("score");
System.out.println(name + ": " + score); }
}
}
}
}

2. Write a program to insert,update,delete and print record for employee having salary
&gt;
20000 from Employee table in database using statement interface.
package java1; import
java.sql.*;
public class EmployeeManagement { public
static void main(String[] args) { try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/EmployeeManagementDB", "root",
"2374");
// Inserting records
insertEmployee(connection, "John", 25000);
insertEmployee(connection, "Alice", 22000);
insertEmployee(connection, "Bob", 18000);
// Updating records
updateEmployeeSalary(connection, "Alice", 23000);

// Deleting a record
NAME- SAIYED MOHAMMADSADAB
ENROLMENT: 211260107010
deleteEmployee(connection, "Bob");
// Printing employees with salary > 20000
printEmployeesWithSalaryGreaterThan(connection, 20000);
connection.close();
} catch (Exception e) { System.out.println(e);
}
}
private static void insertEmployee(Connection connection, String name, int
salary) { try
{
Statement statement = connection.createStatement();
String sql = "INSERT INTO Employee (name, salary) VALUES ('" + name +
"', " + salary + ")";
int rowsAffected = statement.executeUpdate(sql);
System.out.println(rowsAffected + " record(s) inserted for " + name);
statement.close();
} catch (SQLException e) {
System.out.println("Error while inserting record for " + name + ": " +
e.getMessage());
}
}
private static void updateEmployeeSalary(Connection connection, String name,
int newSalary) {
try {
Statement statement = connection.createStatement();
String sql = "UPDATE Employee SET salary = " + newSalary + " WHERE
name = '" + name + "'"; int rowsAffected =
statement.executeUpdate(sql); if (rowsAffected >
0) {
System.out.println("Updated salary for " + name);
} else {
System.out.println("No record found for " + name);
}
statement.close();
} catch (SQLException e) {
System.out.println("Error while updating salary for " + name + ": " +
e.getMessage());
}
}
private static void deleteEmployee(Connection connection, String name) { try
{
Statement statement = connection.createStatement();
String sql = "DELETE FROM Employee WHERE name = '" + name +
"'"; int rowsAffected = statement.executeUpdate(sql); if
(rowsAffected > 0) {
System.out.println("Deleted record for " + name);
} else {
System.out.println("No record found for " + name);
}
statement.close();
} catch (SQLException e) {
System.out.println("Error while deleting record for " + name + ": " +
e.getMessage());
}
}
private static void printEmployeesWithSalaryGreaterThan(Connection connection,
int thresholdSalary) {
try {

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
Statement statement = connection.createStatement(); String
sql = "SELECT * FROM Employee WHERE salary > " +
thresholdSalary;
ResultSet resultSet = statement.executeQuery(sql); System.out.println("Employees
with salary greater than " +
thresholdSalary + ":"); while
(resultSet.next()) {
String name = resultSet.getString("name");
int salary = resultSet.getInt("salary");
System.out.println(name + ": " + salary);
}
statement.close();
} catch (SQLException e) {
System.out.println("Error while printing employees with salary greater
than " + thresholdSalary + ": " + e.getMessage()); }
}
}

QUIZ:

1. What is JDBC? What are the various types of JDBC Driver?

JDBC (Java Database Connectivity) is an API in Java that enables Java programs to interact with
relational databases. It provides a standardized way to perform database operations like querying,
inserting, updating, and retrieving data.

• Various types of JDBC drivers are available:

1. JDBC-ODBC Bridge Driver: Acts as a bridge between JDBC and ODBC APIs. Uses native code and
requires an ODBC driver.

2. Native API (JDBC-Native) Driver: Interacts directly with the database's native API or client library.
Offers high performance but is platform-dependent.

3. Network Protocol Driver (Middleware Driver): Uses a middleware or network protocol to


communicate with the database server. Provides database independence and supports remote servers.

4. Thin Driver (JDBC-Net Pure Java Driver): A pure Java implementation that communicates directly
with the database server using a database-specific network protocol. Doesn't require client-side libraries
or native code.

2. State the difference between Statement vs Prepared Statement vs Callable


Statement.

Statement:
NAME- SAIYED MOHAMMADSADAB
ENROLMENT: 211260107010
1. Used for executing static SQL statements at runtime.

2. SQL queries are directly embedded in the Java code.

3. SQL statements are compiled and executed every time they are invoked.

4. Vulnerable to SQL injection attacks as input values are directly concatenated into the SQL query.
• PreparedStatement:

1. Used for executing parameterized SQL statements.

2. SQL queries are precompiled once and can be reused with different parameter values.

3. Provides better performance compared to `Statement` as the SQL statement is prepared only once.

4. Helps prevent SQL injection attacks by separating SQL code from input values.

• CallableStatement:

1. Used for executing stored procedures in a database.

2. Supports both input and output parameters.

3. Can return multiple result sets.

4. Provides an interface to call stored procedures and retrieve their results.

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
5.

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
Experiment-4:
EXERCISE:
1. Design a form to input details of an employee and submit the data to a servlet. Write code for servlet
that will save the entered details as a new record in database table Employee with fields (EmpId,
EName,Email, Age)

<!DOCTYPE html>
<html>
<head>
<title>Employee Details Form</title>
</head>
<body>
<h2>Employee Details Form</h2>
<form action="EmployeeServlet" method="post">
<label for="empId">Employee ID:</label>
<input type="text" id="empId" name="empId"><br><br>

<label for="empName">Employee Name:</label>


<input type="text" id="empName" name="empName"><br><br>

<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>

<label for="age">Age:</label>
<input type="number" id="age" name="age"><br><br>

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


</form>
</body>
</html>

import java.io.IOException;
import java.io.PrintWriter; import
java.sql.Connection; import
java.sql.DriverManager; import
java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException; import


javax.servlet.annotation.WebServlet; import
javax.servlet.http.HttpServlet; import
javax.servlet.http.HttpServletRequest; import
javax.servlet.http.HttpServletResponse;

@WebServlet("/EmployeeServlet") public class


EmployeeServlet extends HttpServlet { private
static final long serialVersionUID = 1L;

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

// Retrieving form data


String empId = request.getParameter("empId");
String empName = request.getParameter("empName");
String email = request.getParameter("email");
int age = Integer.parseInt(request.getParameter("age"));

// Database connection parameters


String url = "jdbc:mysql://localhost:3306/your_database_name";
String user = "your_username";
String password = "your_password";

try {
// Loading JDBC driver
Class.forName("com.mysql.jdbc.Driver");

// Establishing connection
Connection conn = DriverManager.getConnection(url, user, password);

// SQL query to insert employee details


String sql = "INSERT INTO Employee (EmpId, EName, Email, Age) VALUES (?, ?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, empId); pstmt.setString(2,
empName); pstmt.setString(3, email);
pstmt.setInt(4, age);

// Executing the query


int rowsAffected = pstmt.executeUpdate();
if (rowsAffected > 0) {
out.println("<h3>Employee details saved successfully!</h3>");
} else {
out.println("<h3>Error saving employee details!</h3>");
}

// Closing resources
pstmt.close(); conn.close();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace(); out.println("<h3>Error: " +
e.getMessage() + "</h3>");
}
}
}

Output:

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
2.Write a servlet RegistrationServlet to get the values from registration.html html page and
display the contents. Write the web.xml file

import java.io.IOException; import java.io.PrintWriter;

import javax.servlet.ServletException; import


javax.servlet.annotation.WebServlet; import
javax.servlet.http.HttpServlet; import
javax.servlet.http.HttpServletRequest; import
javax.servlet.http.HttpServletResponse;

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
@WebServlet("/RegistrationServlet") public class
RegistrationServlet extends HttpServlet { private
static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {
response.setContentType("text/html"); PrintWriter out =
response.getWriter();

// Retrieving form data String username =


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

// Displaying the form data


out.println("<html><head><title>Registration
Details</title></head><body>");
out.println("<h2>Registration Details</h2>");
out.println("<p>Username: " + username + "</p>");
out.println("<p>Email: " + email + "</p>");
out.println("<p>Password: " + password + "</p>");
out.println("</body></html>");
}
}

Web.xml:

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


xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID"
version="4.0"> <display-name>RegistrationApp</display-name> <servlet>
<servlet-name>RegistrationServlet</servlet-name> <servlet-
class>RegistrationServlet</servlet-class> </servlet> <servlet-mapping>
<servlet-name>RegistrationServlet</servlet-name> <url-
pattern>/RegistrationServlet</url-pattern> </servlet-mapping> </web-app>

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
3.Write a program to show use of ServletConfig and ServletContext.

import javax.servlet.ServletConfig; import


javax.servlet.ServletContext; import
javax.servlet.ServletException; import
javax.servlet.annotation.WebServlet; import
javax.servlet.http.HttpServlet; import
javax.servlet.http.HttpServletRequest; import
javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/ConfigContextServlet") public class ConfigContextServlet


extends HttpServlet {

private static final long serialVersionUID = 1L;

private ServletConfig servletConfig;


private ServletContext servletContext;

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
@Override public void init(ServletConfig config) throws
ServletException { super.init(config); servletConfig = config;
servletContext = config.getServletContext();
}

protected void doGet(HttpServletRequest request,


HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html"); PrintWriter out =
response.getWriter();

// Accessing parameters from ServletConfig String servletName =


servletConfig.getServletName(); String driver =
servletConfig.getInitParameter("driver"); String url =
servletConfig.getInitParameter("url");

out.println("<html><head><title>Servlet Config and Context


Example</title></head><body>");
out.println("<h2>Servlet Config and Context Example</h2>");
out.println("<p>Servlet Name: " + servletName + "</p>");
out.println("<p>Driver: " + driver + "</p>");
out.println("<p>URL: " + url + "</p>");

// Accessing attributes from ServletContext


servletContext.setAttribute("attributeName", "attributeValue"); String
attributeValue = (String) servletContext.getAttribute("attributeName");
out.println("<p>Attribute Value from ServletContext: " + attributeValue +
"</p>");

out.println("</body></html>");
}
}

Xml:

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
<servlet> <servlet-name>ConfigContextServlet</servlet-name> <servlet-
class>ConfigContextServlet</servlet-class> <init-param> <param-
name>driver</param-name> <param-
value>com.mysql.jdbc.Driver</param-value> </init-param> <init-param>
<param-name>url</param-name> <param-
value>jdbc:mysql://localhost:3306/mydatabase</param-value> </init-
param> </servlet> <servlet-mapping> <servlet-
name>ConfigContextServlet</servlet-name> <url-
pattern>/ConfigContextServlet</url-pattern> </servlet-mapping> <context-
param> <param-name>contextParamName</param-name> <param-
value>contextParamValue</param-value> </context-param>

4.Write a Login servlet. Take input username and password from html file
login.html and authenticate the user. Write the web.xml.

import java.io.IOException; import java.io.PrintWriter;

import javax.servlet.ServletException; import


javax.servlet.annotation.WebServlet; import
javax.servlet.http.HttpServlet; import
javax.servlet.http.HttpServletRequest; import
javax.servlet.http.HttpServletResponse;

@WebServlet("/LoginServlet") public class


LoginServlet extends HttpServlet { private
static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {
response.setContentType("text/html"); PrintWriter out =
response.getWriter();

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
// Hardcoded username and password for demonstration String
username = "admin"; String password = "admin123";

// Retrieving username and password from the login form String


enteredUsername = request.getParameter("username"); String
enteredPassword = request.getParameter("password");

// Authentication logic
if (enteredUsername.equals(username) &&
enteredPassword.equals(password)) {
out.println("<html><head><title>Login Successful</title></head><body>");
out.println("<h2>Login Successful</h2>");
out.println("</body></html>"); } else {
out.println("<html><head><title>Login Failed</title></head><body>");
out.println("<h2>Login Failed. Please check your username and
password.</h2>"); out.println("</body></html>");
}
}
}

Html code:

<!DOCTYPE html> <html> <head> <title>Login</title> </head> <body>


<h2>Login</h2> <form action="LoginServlet" method="post"> <label
for="username">Username:</label> <input type="text" id="username"
name="username"><br><br>

<label for="password">Password:</label> <input type="password"


id="password" name="password"><br><br>

<input type="submit" value="Login"> </form> </body> </html>

Xml code:

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


xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
id="WebApp_ID" version="4.0"> <display-
name>LoginApp</display-name>
<servlet> <servlet-name>LoginServlet</servlet-name> <servlet-
class>LoginServlet</servlet-class> </servlet> <servlet-mapping>
<servlet-name>LoginServlet</servlet-name> <url-
pattern>/LoginServlet</url-pattern> </servlet-mapping> <welcome-file-list>
<welcome-file>login.html</welcome-file> </welcome-file-list> </web-app>

QUIZ:
1. State the difference between GenericServlet vs HttpServlet.

After Entering Correct Username and Paasword

Feature GenericServlet HttpServlet

Suitable for developing Specifically designed for handling HTTP


Intended Use Case protocolindependent servlets requests

Methods and Provides specific methods for handling HTTP


Functionality Provides a generic service() method requests

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
init() , destroy() , getServletInfo() can be doGet() , doPost() , doPut() , doDelete() , etc.
overridden as needed methods for HTTP-specific handling

Protocols other than HTTP, or as a base Web applications running on web servers,
Typical Use class for custom servlets interacting with web browsers via HTTP

2. State the difference between doGet() vs doPost().

Feature doGet() doPost()

HTTP Request
Type Handles HTTP GET requests. Handles HTTP POST requests.

Data Sends data in the URL query string (visible in the Sends data in the request body (not visible
Transmission URL). in the URL).

Limited by the maximum length of a URL (around Not limited by URL length. Typically used
Data Size Limit 2000 characters). for larger data sets.

Less secure for sensitive data because data is More secure for sensitive data because
Security visible in the URL. data is not visible in the URL.

May be cached by web browsers and Typically not cached, although caching can
Caching intermediaries (like proxies). be implemented programmatically.

Generally considered idempotent (repeated


requests with the same parameters yield the same Not inherently idempotent (repeated
Idempotent result). requests may have different effects).

3. State the difference between Servlets vs CGI.

Feature Servlets CGI

Can be written in various languages like Perl,


Language Typically written in Java. Python, etc.

Generally faster and more efficient due to


persistent servlet instances and Slower as each CGI script typically spawns a
Performance multithreading. new process for each request.

Consumes more system resources due to the


Resource Consumes less system resources as servlet overhead of spawning new processes for each
Consumption instances are pooled and reused. request.

More scalable as servlet instances can be Less scalable due to the overhead of spawning
Scalability pooled and reused across multiple new processes for each request.

Feature Servlets CGI

requests.

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
Typically relies on external mechanisms for
Supports various mechanisms for session state management (e.g., cookies, hidden form
State Management management (e.g., HttpSession). fields).

Portable across different platforms as they Less portable as they are executed as separate
Platform run within a servlet container (e.g., Tomcat). processes and may depend on server
Dependency configuration.

Servlet containers handle errors and Error handling is typically left to the CGI script
Error Handling manage the lifecycle of servlets. itself.

Servlet containers provide built-in security


features (e.g., authentication, Security features must be implemented
Security authorization). manually within the CGI script.

Integration with Integrated with web servers through servlet Invoked by the web server as standalone
Web Servers containers (e.g., Apache Tomcat). processes.

4. State the difference between Session and Cookie.

Feature Session Cookie

Storage
Location Stored on the server Stored on the client-side (browser)

Used to maintain stateful information across Used to store small pieces of data on the
multiple requests from the same client/browser client-side that persist across multiple requests
Purpose within a session and sessions

Can be scoped to a specific domain, path, or


even the entire website (depending on cookie
Scope Limited to a single user session attributes)

Can have an expiration date/time set by the


Expires when the session ends or after a specified server or be session-only (deleted when the
Expiry period of inactivity browser is closed)

Size Limit No inherent size limit Limited to 4KB per cookie (per domain)

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
NAME- SAIYED MOHAMMADSADAB
ENROLMENT: 211260107010
Experiment: 5
QUIZ:

1. Draw Servlet life cycle.

Initialization
(init() method)

Service
(service() method)

Destruction
(destroy() method)

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
2. Difference Between Web Server Vs. Application Server.

Feature Web Server Application Server

Primarily designed to serve static content Designed to deploy, manage, and execute dynamic
(e.g., HTML, CSS, images) and handle web applications, which may include business
Purpose HTTP requests. logic, database access, etc.

Provides additional features beyond serving web


Focuses on serving web pages, handling pages, such as support for dynamic content
HTTP requests and responses, and generation, application deployment, transaction
Functionality managing static content. management, security, clustering, etc.

Apache Tomcat, WildFly (formerly JBoss), IBM


Examples Apache HTTP Server, Nginx, Microsoft IIS WebSphere, Oracle WebLogic

Typically supports static content and may Supports a wide range of server-side technologies
offer support for dynamic content using such as Servlets, JSP, ASP.NET, EJB, PHP, etc., for
Supported server-side technologies like CGI, PHP, or developing and executing dynamic web
Technologies server-side scripting languages. applications.

Generally more lightweight and suited for Designed to handle complex enterprise-level
handling large volumes of static content applications with scalability features like clustering,
Scalability and simple web applications. load balancing, and distributed computing.

May have slightly higher overhead due to


Optimized for serving static content additional features and services, but optimized for
efficiently, making them faster for tasks executing complex business logic and database
Performance such as serving static files or caching. operations efficiently.

Typically used as front-end servers, often Used to deploy and execute dynamic web
in combination with application servers, applications, often in conjunction with web servers
Deployment reverse proxies, or caching servers. acting as front-end servers.

Limited support for dynamic content


Dynamic generation, often relying on server-side Provides robust support for dynamic content
Content scripting languages or CGI for dynamic generation using server-side technologies such as
Generation functionality. Servlets, JSP, ASP.NET, etc.

Offers advanced management and monitoring


capabilities for deploying, managing, and
Basic management and monitoring monitoring applications, including features like
Management capabilities, focused on serving HTTP application deployment, transaction management,
and Monitoring requests and maintaining server uptime. clustering, etc.

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
EXPERIMENT 7
EXERCISE:

1. Write a JSP program using JSTL SQL taglib to display student details in tabular form by
iterating through the database table student.

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


pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<title>Student Details</title>
</head>
<body>
<h1>Student Details</h1>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Grade</th>
</tr>
</thead>
<tbody>
<sql:setDataSource var="dataSource" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/your_database_name" user="your_username"
password="your_password" />
<sql:query dataSource="${dataSource}" var="result">
SELECT * FROM student;
</sql:query>
<c:forEach var="row" items="${result.rows}">
<tr>
<td><c:out value="${row.id}" /></td>
<td><c:out value="${row.name}" /></td>
<td><c:out value="${row.age}" /></td>
<td><c:out value="${row.grade}" /></td>
</tr>
</c:forEach>
</tbody>
</table>

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
</body>
</html>

QUIZ:
1. What is JSP directives with examples.

JSP directives are special instructions that guide the web container on how to
Syntax:
<%@ directive attribute = "value"%>
translate a JSP (Java Server Pages) page into its corresponding servlet. These
directives are essential for controlling the processing of an entire JSP page.

There are three different JSP directives available. They are as follows:
1. Page Directive
2. Include Directive
3. Taglib Directive

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
2. What is JSTL?

JSTL (JavaServer Pages Standard Tag Library) is a collection of custom tags that
encapsulate common functionality for JavaServer Pages (JSP) development. It provides
a set of tags for performing tasks such as iteration, conditional logic, database access,
XML processing, and internationalization, among others.

3. Advantages of JSTL

Simplicity: JSTL simplifies JSP development by providing a set of easy-to-use,


high-level tags that encapsulate common tasks. This reduces the need for writing
complex Java code directly within JSP files, leading to cleaner and more
maintainable code.

Standardization: JSTL is a standard library that is supported by all compliant JSP


containers. This ensures portability and interoperability across different web
application servers and environments.

Modularity: JSTL promotes modular development by allowing developers to


focus on the presentation layer separately from the business logic. This separation
of concerns leads to more manageable codebases and facilitates team
collaboration.

Reuse: JSTL encourages the reuse of code through its tag libraries. Developers
can create custom tags or use built-in tags to encapsulate common functionality,
making it easier to maintain and update code across multiple pages.

Reduced Errors: By providing a declarative approach to common tasks such as


iteration, conditional logic, and error handling, JSTL reduces the likelihood of
errors that may arise from manual coding. This improves the robustness and
reliability of web applications.

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
NAME- SAIYED MOHAMMADSADAB
ENROLMENT: 211260107010
Experiment 8:
Quiz:
1. What are basic tags of JSF?

<h:form>: This tag is used to define a form in JSF. It encapsulates a set of input
components and allows developers to submit data to the server.

<h:inputText>: This tag is used to create an input field for text input. It allows
users to enter text data, such as a username or password.

<h:outputText>: This tag is used to display static text on a JSF page. It can be
used to output dynamic data from a managed bean as well.

<h:commandButton>: This tag is used to create a button that submits a form when
clicked. It is commonly used for form submission in JSF applications.

<h:outputLabel>: This tag is used to create a label for an input component. It


associates the label with the corresponding input field, improving accessibility
and usability.

2. What is JSF?

JSF (JavaServer Faces) is a Java-based web application framework developed by


Oracle (formerly Sun Microsystems) for building user interfaces for web
applications. It is part of the Java EE (Enterprise Edition) platform and provides a
component-based model for developing web applications.

3. Advantages of JSF

Component-Based Architecture: JSF follows a component-based architecture,


where UI components are defined in a modular and reusable manner. This
NAME- SAIYED MOHAMMADSADAB
ENROLMENT: 211260107010
promotes code reusability, maintainability, and scalability, as developers can
easily create custom components and assemble them to build complex user
interfaces.

Rich Component Library: JSF provides a rich set of built-in UI components for
common tasks such as input fields, buttons, tables, forms, and more. These
components are highly customizable and can be easily extended or combined to
create sophisticated user interfaces with minimal effort.

Event-Driven Programming Model: JSF follows an event-driven programming


model, where user interactions trigger events that are handled by server-side code.
This model simplifies the development of interactive and dynamic web
applications, allowing developers to focus on handling user interactions without
worrying about low-level HTTP details.

Server-Side State Management: JSF manages the state of user interfaces on the
server-side, which eliminates the need for developers to manually manage
clientside state. This simplifies development and improves scalability, as server-
side state management can better handle concurrent user sessions and large
volumes of data.

Integration with Java EE Technologies: JSF seamlessly integrates with other Java
EE technologies such as JPA (Java Persistence API), EJB (Enterprise JavaBeans),
JMS (Java Message Service), and CDI (Contexts and Dependency Injection). This
allows developers to leverage the full power of the Java EE platform to build
robust and enterprise-grade web applications.

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
Experiment 9:
QUIZ:
1. What is hibernate? List the advantages of hibernate over JDBC?

Hibernate is an open-source, object-relational mapping (ORM) framework for Java that


simplifies the development of database-driven applications. It provides a framework for
mapping Java objects to database tables and vice versa, allowing developers to work with
objects rather than low-level SQL statements.

Here are some advantages of Hibernate over JDBC:

Object-Relational Mapping (ORM): Hibernate provides a powerful ORM mechanism that


maps Java objects to database tables, eliminating the need for developers to write tedious and
error-prone SQL queries. This abstraction simplifies database interaction and allows
developers to work with objects instead of dealing with relational database concepts directly.

Productivity: Hibernate significantly improves developer productivity by reducing the amount


of boilerplate code needed to interact with the database. With Hibernate, developers can focus
on writing business logic rather than spending time on database-related tasks such as SQL
query optimization and result set handling.

Automatic CRUD Operations: Hibernate automatically generates SQL queries for CRUD
(Create, Read, Update, Delete) operations based on the mappings defined in the entity classes.
This reduces the amount of repetitive code that developers need to write and maintain,
leading to cleaner and more maintainable codebases.

2. What is O/R mapping?


Object-Relational Mapping (O/R mapping or ORM) is a programming technique that allows
developers to map objects in object-oriented programming languages (such as Java, C#,
Python) to data stored in relational databases. It bridges the gap between the object-oriented

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
programming paradigm and the relational database model, enabling developers to work with
objects in their code while persisting and retrieving data from a relational database.

3. What is HQL? What are advantages of HQL?

HQL (Hibernate Query Language) is a powerful object-oriented query language


provided by the Hibernate ORM framework. It is similar to SQL (Structured
Query Language) but operates on persistent objects rather than database tables.
HQL allows developers to write database queries in a more object-oriented and
expressive manner, making it easier to work with complex data models.

Advantages of HQL include:

Object-Oriented Queries: HQL allows developers to write queries using familiar


object-oriented concepts such as classes, properties, and associations. This makes
it easier to express complex relationships and criteria in a natural and intuitive
way.

Database Independence: HQL abstracts away database-specific SQL syntax and


features, allowing developers to write database-independent queries. This means
that the same query can be executed on different database platforms without
requiring changes to the underlying SQL code.

Type Safety: HQL provides type safety at compile time, reducing the risk of
runtime errors caused by mismatched data types or invalid SQL syntax. This
improves code reliability and maintainability, as errors can be caught early in the
development process.

Support for Object Graph Navigation: HQL supports navigation of object graphs,
allowing developers to traverse associations between persistent objects in their
queries. This makes it easy to retrieve related objects and navigate complex data
structures without resorting to multiple SQL queries or manual object loading.

Criteria Queries: HQL supports criteria queries, which allow developers to build
dynamic queries based on runtime conditions and parameters. Criteria queries
provide a flexible and powerful way to construct queries dynamically, making it
easier to handle complex

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
Experiment 10:
QUIZ:

1. What is Spring IoC container?


The Spring IoC (Inversion of Control) container is a core component of the Spring
Framework that manages the creation, configuration, and lifecycle of objects (also known as
beans) in a Spring-based application. IoC is a design principle where the control of object
creation and dependency injection is shifted from the application code to the container or
framework.

2. What is spring?
Spring is a powerful and widely used open-source application framework for Java. It provides
comprehensive infrastructure support for developing Java applications, ranging from simple
standalone applications to complex enterprise-level applications. Spring is known for its
lightweight nature, modularity, and support for a wide range of functionalities, including
dependency injection, aspect-oriented programming, transaction management, and more.

3. What are the types of Dependency Injection Spring supports?


Spring supports several types of dependency injection, allowing developers to
choose the most suitable approach based on their application's requirements and
preferences.

The main types of dependency injection supported by Spring are:

A. Constructor Injection:

In constructor injection, dependencies are provided to a class through its


constructor.

The Spring IoC container instantiates the bean and injects its dependencies by
invoking the constructor with the required parameters.

Constructor injection is useful for mandatory dependencies that must be initialized


when the object is created.

Example:

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
public class MyClass { private Dependency dependency;

public MyClass(Dependency dependency) { this.dependency =


dependency;
}
}

B. Setter Injection:

In setter injection, dependencies are provided to a class through setter methods.

The Spring IoC container instantiates the bean and injects its dependencies by
invoking the appropriate setter methods.

Setter injection is useful for optional dependencies or when there are multiple
dependencies to be injected.

Example:

public class MyClass { private Dependency dependency;

public void setDependency(Dependency dependency) {


this.dependency = dependency;
}
}

C. Field Injection:

In field injection, dependencies are directly injected into class fields using
annotations.

The Spring IoC container injects the dependencies directly into the annotated
fields, bypassing constructors or setter methods.

Field injection is convenient but may lead to tight coupling and is not
recommended for mandatory dependencies.

Example:

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010
public class MyClass {
@Autowired private Dependency
dependency;
}

D. Method Injection:

In method injection, dependencies are provided to a class through special callback


methods.

The Spring IoC container injects the dependencies by invoking the callback
methods with the required parameters.

Method injection is less common and is typically used for more advanced
scenarios where the dependency may change dynamically at runtime.

Example:

public class MyClass { private Dependency dependency;

@Autowired public void setDependency(Dependency dependency) {


this.dependency = dependency;
}
}

Spring supports all these types of dependency injection through its IoC container,
allowing developers to choose the most appropriate approach based on their
application's design and requirements.

NAME- SAIYED MOHAMMADSADAB


ENROLMENT: 211260107010

You might also like