Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 41

1. Illustrate the importance of Class.forName() and DriverManager.

getConnection()
methods of JDBC API
Importance of Class.forName():
The Class.forName() method is used to dynamically load the JDBC driver class into memory.
In JDBC, each database vendor provides its own implementation of the JDBC driver, which is
responsible for facilitating communication between the Java application and the specific
database management system (DBMS). By using Class.forName(), the driver class is loaded
and registered with the DriverManager, allowing it to be used to establish connections to the
corresponding database.

try {
// Dynamically load the JDBC driver class
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Importance of DriverManager.getConnection():
The DriverManager.getConnection() method is used to establish a connection to the database
using the registered JDBC driver. It takes a database URL, username, and password as
parameters and returns a Connection object representing the connection to the database. This
connection object is then used to create statements, execute queries, and perform other
database operations.

try {
// Establish connection to the database
Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydatabase", "username", "password");

// Perform database operations using the connection


// ...

// Close the connection when done


connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
2. List out the advantages of Type IV JDBC Driver
A Type IV JDBC (Java Database Connectivity) driver, also known as the "thin driver" or
"pure Java driver," is a JDBC driver type that communicates directly with the database server
without requiring any native code or middleware. Here are some advantages of using a Type
IV JDBC Driver:

Platform Independence: Type IV drivers are written entirely in Java, making them platform-
independent. They can run on any platform that supports Java, including Windows, Linux,
macOS, etc. This eliminates the need for platform-specific libraries or configurations.

No Client Installation: Type IV drivers do not require any client-side installation. Since they
are pure Java implementations, they can be distributed along with the application code. This
simplifies deployment and reduces dependencies, making it easier to manage and maintain
applications.
Optimal Performance: Type IV drivers offer optimal performance because they communicate
directly with the database server using the native network protocols provided by the database
vendor. There is no intermediate translation layer, which can introduce overhead and affect
performance. This direct communication minimizes latency and improves response times.

Security: Type IV drivers provide secure communication between the Java application and
the database server. They typically support encryption and authentication mechanisms
provided by the database vendor, ensuring the confidentiality and integrity of data transmitted
over the network.

Scalability: Type IV drivers are scalable and can handle high volumes of database
connections efficiently. They leverage the scalability features of the underlying Java platform
and database server, allowing applications to scale seamlessly as the workload increases.

Ease of Development: Type IV drivers simplify development by providing a consistent and


familiar JDBC API for database access. Developers can write database-independent code
using standard JDBC interfaces without worrying about the underlying database
implementation details.

Vendor Independence: Type IV drivers promote vendor independence by allowing


applications to connect to multiple databases using the same driver implementation. This
flexibility enables organizations to switch between different database vendors without
modifying the application code.

Support for Advanced Features: Type IV drivers often support advanced features and
functionalities provided by the JDBC specification, such as connection pooling, distributed
transactions, batch updates, and stored procedures. These features enhance the capabilities of
Java applications and improve overall performance and reliability.
3. Compare executeQuery() and executeUpdate() methods of ResultSet object with an
example

4. Develop a JSP script that illustrates the usage of JSP expressions and JSP directives
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-
8" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSP Example</title>
</head>
<body>
<!-- JSP Directive: Using 'page' directive to import a Java package -->
<%@ page import="java.util.Date" %>

<!-- JSP Expression: Displaying the current date and time -->
<h2>Current Date and Time:</h2>
<p><%= new Date() %></p>

<!-- JSP Expression: Arithmetic expression -->


<h2>Arithmetic Expression:</h2>
<p>2 + 3 = <%= 2 + 3 %></p>

<!-- JSP Expression: Concatenating strings -->


<h2>String Concatenation:</h2>
<p>Hello <%= "World" %>!</p>

<!-- JSP Directive: Using 'include' directive to include another JSP file -->
<%@ include file="footer.jsp" %>
</body>
</html>

5. Design the following tables using SQL .Use suitable datatypes and constraints as
specified below in ORACLE database Department(DeptID , Dname ,Location) ;Primary
Key : DeptID Employees (Empid , FirstName, LastName, DeptNo ) ; Primary Key :
EmpID Foreign Key : DeptNo Department(DeptID)
Projects(ProjectID,DeptID,Manager) Foreign Key(s) : DeptID
Department(DeptID);ManagerEmployees(Empid) Write SQL Queries for the following
1. Display all employees working in deptno 20; 2. Display all projects of department 10
3. Display managers of all Projects
-- Create Department table
CREATE TABLE Department (
DeptID INT PRIMARY KEY,
Dname VARCHAR(50),
Location VARCHAR(50)
);

-- Create Employees table


CREATE TABLE Employees (
EmpID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
DeptNo INT,
FOREIGN KEY (DeptNo) REFERENCES Department(DeptID)
);

-- Create Projects table


CREATE TABLE Projects (
ProjectID INT PRIMARY KEY,
DeptID INT,
Manager INT,
FOREIGN KEY (DeptID) REFERENCES Department(DeptID)
);

-- Create ManagerEmployees table


CREATE TABLE ManagerEmployees (
EmpID INT,
FOREIGN KEY (EmpID) REFERENCES Employees(EmpID)
);

-- Sample Data Insertion for testing


INSERT INTO Department (DeptID, Dname, Location) VALUES (10, 'Sales', 'New York');
INSERT INTO Department (DeptID, Dname, Location) VALUES (20, 'Marketing', 'Los
Angeles');

INSERT INTO Employees (EmpID, FirstName, LastName, DeptNo) VALUES (1, 'John',
'Doe', 10);
INSERT INTO Employees (EmpID, FirstName, LastName, DeptNo) VALUES (2, 'Jane',
'Smith', 20);

INSERT INTO Projects (ProjectID, DeptID, Manager) VALUES (101, 10, 1);
INSERT INTO Projects (ProjectID, DeptID, Manager) VALUES (102, 20, 2);

INSERT INTO ManagerEmployees (EmpID) VALUES (1);


INSERT INTO ManagerEmployees (EmpID) VALUES (2);

 Display all employees working in deptno 20:


SELECT * FROM Employees WHERE DeptNo = 20;

 Display all projects of department 10:


SELECT * FROM Projects WHERE DeptID = 10;

 Display managers of all Projects:


SELECT p.ProjectID, e.FirstName, e.LastName
FROM Projects p
JOIN Employees e ON p.Manager = e.EmpID;

6. Assume a table Flights with following fields: ( FlightID, Source, Destination,


DepartureDate , Fare) Write SQL statements to create the above table and • Insert 4
records in to the above table. • Display all flights from Hyderabad• Update the Fare of
Flight AI721 to 8900 • Delete the record of the flight starting from Delhi. • Display all
Flight details departing today. • Display all flights from Mumbai to Vijayawada

-- Create Flights table


CREATE TABLE Flights (
FlightID INT PRIMARY KEY,
Source VARCHAR(50),
Destination VARCHAR(50),
DepartureDate DATE,
Fare DECIMAL(10, 2)
);

-- Insert 4 records into the Flights table


INSERT INTO Flights (FlightID, Source, Destination, DepartureDate, Fare)
VALUES
(1, 'Hyderabad', 'Bangalore', '2024-03-30', 4500.00),
(2, 'Delhi', 'Mumbai', '2024-03-31', 5500.00),
(3, 'Mumbai', 'Chennai', '2024-03-30', 5000.00),
(4, 'Chennai', 'Hyderabad', '2024-03-31', 4800.00);

-- Display all flights from Hyderabad


SELECT * FROM Flights WHERE Source = 'Hyderabad';

-- Update the Fare of Flight AI721 to 8900


UPDATE Flights SET Fare = 8900.00 WHERE FlightID = 1;

-- Delete the record of the flight starting from Delhi


DELETE FROM Flights WHERE Source = 'Delhi';

-- Display all Flight details departing today


SELECT * FROM Flights WHERE DepartureDate = CURRENT_DATE;

-- Display all flights from Mumbai to Vijayawada


SELECT * FROM Flights WHERE Source = 'Mumbai' AND Destination = 'Vijayawada';

7. Define Servlet and Compare Generic Servlet and HTTP Servlet ?


Java Servlets are the Java programs that run on the Java-enabled web server
or application server. They are used to handle the request obtained from the
web server, process the request, produce the response, and then send a
response back to the web server.

GenericServlet HttpServlet
It is defined by javax.servlet package. It is defined by javax.servlethttp package.
It describes protocol-independent servlet It describes protocol-dependent servlet.
GenericServiet is not dependent on any HttpServlet is a dependent protocol and is
particular protocol. It can be used with only used with HTTP protocol.
any protocol such as HTTP, SMTP, FTP,
and so on.
All methods are concrete except the All methods are concrete (non-abstract).
service() method. service() method is an service() is non-abstract method. service()
abstract method. can be replaced by doGet() or doPost()
methods.
GenericServlet HttpServlet
The service method is abstract. The service method is non-abstract
It forwards and includes a request and is It forwards and includes a request but it is
also possible to redirect a request. not possible to redirect the request.
GenericServlet doesn’t allow session HTTPServlet allows session management
management with cookies and HTTP with cookies and HTTP sessions.
sessions.
It is an immediate child class of Servlet It is an immediate child class of
interface. GenericServlet class.
GenericServlet is a superclass of HttpServlet is a subclass of GenericServlet
HttpServlet class. class.

8. Demonstrate a JSP script that illustrates the usage of sendRedirect() method to redirect
the user to another page.
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-
8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Redirect Example</title>
</head>
<body>
<h2>Redirect Example</h2>

<%
// Check some condition (for demonstration)
boolean redirect = true;

if (redirect) {
// Redirect to another page
response.sendRedirect("destination.jsp");
} else {
// Output some content if not redirected
%>
<p>You will not be redirected.</p>
<%
}
%>
</body>
</html>

Destination.jsp

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


8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Destination Page</title>
</head>
<body>
<h2>Welcome to the Destination Page</h2>
<p>This is the page where you have been redirected.</p>
</body>
</html>

9. Assume Customer table in Oracle Database with following fields (CustID, CustName,
Address, Mobile). a) Create a HTML form to enter the data in to above fields along with
submit button. b) Write JSP code to insert data submitted by the user through the above
HTML form into Customer Table.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Customer Registration Form</title>
</head>
<body>
<h2>Customer Registration Form</h2>
<form action="insertCustomer.jsp" method="post">
<label for="custName">Name:</label>
<input type="text" id="custName" name="custName" required><br><br>

<label for="address">Address:</label>
<input type="text" id="address" name="address" required><br><br>

<label for="mobile">Mobile:</label>
<input type="text" id="mobile" name="mobile" required><br><br>

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


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

insertCustomer.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert Customer Data</title>
</head>
<body>
<h2>Insert Customer Data</h2>
<%
// Retrieve form data submitted by the user
String custName = request.getParameter("custName");
String address = request.getParameter("address");
String mobile = request.getParameter("mobile");

// JDBC Connection variables


String url = "jdbc:oracle:thin:@localhost:1521:XE"; // Oracle database URL
String username = "your_username";
String password = "your_password";

// SQL query to insert data into Customer table


String sql = "INSERT INTO Customer (CustName, Address, Mobile) VALUES (?, ?, ?)";

// Establish database connection


try {
Class.forName("oracle.jdbc.driver.OracleDriver"); // Load Oracle JDBC driver
Connection conn = DriverManager.getConnection(url, username, password);

// Create PreparedStatement to execute SQL query


PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, custName);
pstmt.setString(2, address);
pstmt.setString(3, mobile);

// Execute the query


int rowsInserted = pstmt.executeUpdate();
if (rowsInserted > 0) {
out.println("<p>Customer data inserted successfully.</p>");
} else {
out.println("<p>Failed to insert customer data.</p>");
}

// Close PreparedStatement and Connection


pstmt.close();
conn.close();

} catch (Exception e) {
out.println("<p>Error: " + e.getMessage() + "</p>");
}
%>
</body>
</html>
10. Assume Patients Table in Oracle Database with following fields ( PatientID, Pname,
RoomNo, BedNo, RefDoctor, JoinDate). a) Create a HTML Form that prompts the user
to select a Date along with a submit Button. b) Write Servlet code to display all the
patient records who got admitted on a particular date as selected by the user in HTML
form.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Select Admission Date</title>
</head>
<body>
<h2>Select Admission Date</h2>
<form action="PatientRecordsServlet" method="get">
<label for="admissionDate">Select Admission Date:</label>
<input type="date" id="admissionDate" name="admissionDate" required><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

PatientRecordsServlet.java

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@WebServlet("/PatientRecordsServlet")
public class PatientRecordsServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

// Retrieve admission date selected by the user


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

// JDBC Connection variables


String url = "jdbc:oracle:thin:@localhost:1521:XE"; // Oracle database URL
String username = "your_username";
String password = "your_password";

// SQL query to select patient records based on admission date


String sql = "SELECT * FROM Patients WHERE JoinDate = ?";

// Establish database connection


try {
Class.forName("oracle.jdbc.driver.OracleDriver"); // Load Oracle JDBC driver
Connection conn = DriverManager.getConnection(url, username, password);

// Create PreparedStatement to execute SQL query


PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setDate(1, Date.valueOf(admissionDate)); // Convert String date to
java.sql.Date

// Execute the query


ResultSet rs = pstmt.executeQuery();

// Display patient records


out.println("<h2>Patient Records for Admission Date: " + admissionDate + "</h2>");
out.println("<table border='1'>");
out.println("<tr><th>PatientID</th><th>Name</th><th>RoomNo</th><th>BedNo</
th><th>RefDoctor</th><th>JoinDate</th></tr>");
while (rs.next()) {
out.println("<tr>");
out.println("<td>" + rs.getInt("PatientID") + "</td>");
out.println("<td>" + rs.getString("Pname") + "</td>");
out.println("<td>" + rs.getString("RoomNo") + "</td>");
out.println("<td>" + rs.getString("BedNo") + "</td>");
out.println("<td>" + rs.getString("RefDoctor") + "</td>");
out.println("<td>" + rs.getDate("JoinDate") + "</td>");
out.println("</tr>");
}
out.println("</table>");

// Close ResultSet, PreparedStatement, and Connection


rs.close();
pstmt.close();
conn.close();

} catch (Exception e) {
out.println("<p>Error: " + e.getMessage() + "</p>");
}
}
}

11. Develop a Servlet script that receives and display the following data entered by the user
through HTML form - FirstName, LastName and Address.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

@WebServlet("/UserDetailsServlet")
public class UserDetailsServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
// Retrieve user input data
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String address = request.getParameter("address");
// Display user details
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<meta charset=\"UTF-8\">");
out.println("<title>User Details</title>");
out.println("</head>");
out.println("<body>");
out.println("<h2>User Details</h2>");
out.println("<p><strong>First Name:</strong> " + firstName + "</p>");
out.println("<p><strong>Last Name:</strong> " + lastName + "</p>");
out.println("<p><strong>Address:</strong> " + address + "</p>");
out.println("</body>");
out.println("</html>");
}
}
12. Assume Books table in oracle database with following fields ( ISBN, Title, Author, Price)
a) Create a HTML that prompts the user to enter a Book Title and Updated Price along
with a Submit Button. b) Write Servlet code to Update the price of the book entered by
the user.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Update Book Price</title>
</head>
<body>
<h2>Update Book Price</h2>
<form action="UpdateBookPriceServlet" method="post">
<label for="title">Book Title:</label>
<input type="text" id="title" name="title" required><br><br>

<label for="price">Updated Price:</label>


<input type="number" id="price" name="price" min="0" step="0.01"
required><br><br>

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


</form>
</body>
</html>
UpdateBookPriceServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.sql.*;

@WebServlet("/UpdateBookPriceServlet")
public class UpdateBookPriceServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

// Retrieve book title and updated price entered by the user


String title = request.getParameter("title");
double price = Double.parseDouble(request.getParameter("price"));

// JDBC Connection variables


String url = "jdbc:oracle:thin:@localhost:1521:XE"; // Oracle database URL
String username = "your_username";
String password = "your_password";

// SQL query to update book price


String sql = "UPDATE Books SET Price = ? WHERE Title = ?";

// Establish database connection


try {
Class.forName("oracle.jdbc.driver.OracleDriver"); // Load Oracle JDBC driver
Connection conn = DriverManager.getConnection(url, username, password);

// Create PreparedStatement to execute SQL query


PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setDouble(1, price);
pstmt.setString(2, title);

// Execute the query


int rowsUpdated = pstmt.executeUpdate();
if (rowsUpdated > 0) {
out.println("<p>Price updated successfully for book: " + title + "</p>");
} else {
out.println("<p>Failed to update price for book: " + title + "</p>");
}

// Close PreparedStatement and Connection


pstmt.close();
conn.close();

} catch (Exception e) {
out.println("<p>Error: " + e.getMessage() + "</p>");
}
}
}

13. Assume Customers table in oracle database with following fields ( CustID, CName, City,
Mobile) a) Create a HTML form that prompts the user to select city from a drop down
list along with submit button. b) Write JSP code to display the records of all customers
who belongs to that city as selected by the user through the HTML form.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Select City</title>
</head>
<body>
<h2>Select City</h2>
<form action="DisplayCustomers.jsp" method="post">
<label for="city">Select City:</label>
<select id="city" name="city">
<option value="New York">New York</option>
<option value="Los Angeles">Los Angeles</option>
<option value="Chicago">Chicago</option>
<!-- Add more city options as needed -->
</select><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

DisplayCustomers.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-
8"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Customers in City</title>
</head>
<body>
<h2>Customers in City</h2>
<%
// Retrieve selected city from the form
String city = request.getParameter("city");

// JDBC Connection variables


String url = "jdbc:oracle:thin:@localhost:1521:XE"; // Oracle database URL
String username = "your_username";
String password = "your_password";

// SQL query to select customers in the selected city


String sql = "SELECT * FROM Customers WHERE City = ?";

// Establish database connection


try {
Class.forName("oracle.jdbc.driver.OracleDriver"); // Load Oracle JDBC driver
Connection conn = DriverManager.getConnection(url, username, password);

// Create PreparedStatement to execute SQL query


PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, city);

// Execute the query


ResultSet rs = pstmt.executeQuery();

// Display customer records


out.println("<table border='1'>");
out.println("<tr><th>CustID</th><th>CName</th><th>City</th><th>Mobile</th></
tr>");
while (rs.next()) {
out.println("<tr>");
out.println("<td>" + rs.getInt("CustID") + "</td>");
out.println("<td>" + rs.getString("CName") + "</td>");
out.println("<td>" + rs.getString("City") + "</td>");
out.println("<td>" + rs.getString("Mobile") + "</td>");
out.println("</tr>");
}
out.println("</table>");

// Close ResultSet, PreparedStatement, and Connection


rs.close();
pstmt.close();
conn.close();

} catch (Exception e) {
out.println("<p>Error: " + e.getMessage() + "</p>");
}
%>
</body>
</html>

14. Build JSP code to validate the mobile number entered by the user. A VALID mobile
number has exactly 10 digits. If the mobile number is valid display the message “
Thanks for providing your contact number” else display the message “ Invalid Mobile
Number”.

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


8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Mobile Number Validation</title>
</head>
<body>
<h2>Mobile Number Validation</h2>
<form action="MobileNumberValidation.jsp" method="post">
<label for="mobile">Enter Mobile Number:</label>
<input type="text" id="mobile" name="mobile" required><br><br>
<input type="submit" value="Validate">
</form>
<%
String mobileNumber = request.getParameter("mobile");
String message = "";

// Check if mobile number is exactly 10 digits


if (mobileNumber != null && mobileNumber.length() == 10 &&
mobileNumber.matches("\\d+")) {
message = "Thanks for providing your contact number";
} else {
message = "Invalid Mobile Number";
}

// Display validation message


out.println("<p>" + message + "</p>");
%>
</body>
</html>

15. Assume Users table in oracle database with following fields ( Username, Password) a)
Create a HTML form with Username and password Fields along with submit button. b)
Develop JSP code that validates the username and password fields and displays a
welcome message for a valid user. (Assume a record with username as ‘admin’ and
password as “admin123’)

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login Form</title>
</head>
<body>
<h2>Login Form</h2>
<form action="LoginValidation.jsp" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br><br>

<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>

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


</form>
</body>
</html>
LoginValidation.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-
8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login Validation</title>
</head>
<body>
<h2>Login Validation</h2>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");

// Hardcoded valid credentials


String validUsername = "admin";
String validPassword = "admin123";

// Validate username and password


if (username != null && password != null && username.equals(validUsername) &&
password.equals(validPassword)) {
// Display welcome message for valid user
%>
<p>Welcome, <%= username %>!</p>
<%
} else {
// Display error message for invalid user
%>
<p>Invalid username or password. Please try again.</p>
<%
}
%>
</body>
</html>

16. Explain the architecture of JDBC

Architecture of JDBC
Description:
1. Application: It is a java applet or a servlet that communicates with a data
source.
2. The JDBC API: The JDBC API allows Java programs to execute SQL
statements and retrieve results. Some of the important classes and
interfaces defined in JDBC API are as follows:
3. DriverManager: It plays an important role in the JDBC architecture. It
uses some database-specific drivers to effectively connect enterprise
applications to databases.
4. JDBC drivers: To communicate with a data source through JDBC, you
need a JDBC driver that intelligently communicates with the respective
data source.
Types of JDBC Architecture(2-tier and 3-tier)
The JDBC architecture consists of two-tier and three-tier processing models to
access a database. They are as described below:
1. Two-tier model: A java application communicates directly to the data
source. The JDBC driver enables the communication between the
application and the data source. When a user sends a query to the data
source, the answers for those queries are sent back to the user in the form
of results.
The data source can be located on a different machine on a network to
which a user is connected. This is known as a client/server
configuration, where the user’s machine acts as a client, and the machine
has the data source running acts as the server.

2. Three-tier model: In this, the user’s queries are sent to middle-tier


services, from which the commands are again sent to the data source. The
results are sent back to the middle tier, and from there to the user.
This type of model is found very useful by management information
system directors.

17. Summarize various types of Statement objects used in JDBC

In JDBC (Java Database Connectivity), there are three main types of Statement objects that
can be used to execute SQL queries and commands against a database:

Statement: This is the simplest type of Statement object, suitable for executing simple SQL
queries without parameters. It can execute SQL statements that do not contain input
parameters or return multiple results. However, it is vulnerable to SQL injection attacks and
does not provide good performance for executing the same SQL statement multiple times
with different parameter values.

Example:

Statement statement = connection.createStatement();


ResultSet resultSet = statement.executeQuery("SELECT * FROM table_name");

PreparedStatement: This type of Statement object allows for precompilation of SQL queries
with parameters. It is suitable for executing parameterized SQL queries, where the parameter
values can be set dynamically before execution. PreparedStatement provides better
performance and security compared to Statement, as it prevents SQL injection attacks by
automatically escaping parameters. It is also more efficient for executing the same SQL
statement multiple times with different parameter values.

Example:

PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM


table_name WHERE column_name = ?");
preparedStatement.setString(1, "parameter_value");
ResultSet resultSet = preparedStatement.executeQuery();

CallableStatement: This type of Statement object is used to execute stored procedures or


functions in the database. It allows for execution of SQL statements that are precompiled and
stored in the database server. CallableStatement is suitable for executing stored procedures or
functions that may return multiple result sets or have output parameters.

Example:
CallableStatement callableStatement = connection.prepareCall("{call
procedure_name(?, ?)}");
callableStatement.setString(1, "input_parameter");
callableStatement.registerOutParameter(2, Types.INTEGER);
callableStatement.execute();
int outputParameter = callableStatement.getInt(2);

18. Develop a java program to select records from a table using JDBC application
import java.sql.*;
public class SelectRecordsExample {
public static void main(String[] args) {
// JDBC Connection variables
String url = "jdbc:mysql://localhost:3306/mydatabase"; // Database URL
String username = "your_username";
String password = "your_password";

// SQL query to select records from EMP table


String sql = "SELECT * FROM EMP";

// Establish database connection


try {
// Load the MySQL JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Create a connection to the database


Connection connection = DriverManager.getConnection(url, username, password);

// Create a statement for executing SQL queries


Statement statement = connection.createStatement();

// Execute the SQL query and get the result set


ResultSet resultSet = statement.executeQuery(sql);

// Process the result set


while (resultSet.next()) {
// Retrieve data from each row
int empId = resultSet.getInt("emp_id");
String empName = resultSet.getString("emp_name");
double salary = resultSet.getDouble("salary");
String department = resultSet.getString("department");
// Print the retrieved data
System.out.println("Employee ID: " + empId);
System.out.println("Employee Name: " + empName);
System.out.println("Salary: " + salary);
System.out.println("Department: " + department);
System.out.println();
}

// Close the result set, statement, and connection


resultSet.close();
statement.close();
connection.close();

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

19. K L University maintains a library of Books written by their faculty members which are
published by different Publishers. Create a JDBC application that helps the librarian to
perform some basic operations like a) Adding a book to the database b) Fetching the
details of the book including the Author information
import java.sql.*;

public class LibraryManagementSystem {


// JDBC URL, username, and password
static final String JDBC_URL = "jdbc:mysql://localhost:3306/library";
static final String USERNAME = "your_username";
static final String PASSWORD = "your_password";

public static void main(String[] args) {


try {
// Establishing a connection to the database
Connection connection = DriverManager.getConnection(JDBC_URL, USERNAME,
PASSWORD);
System.out.println("Connected to the database");

// Adding a book to the database


addBook(connection, "Introduction to Java", "John Smith", "ABC Publications");

// Fetching details of a book


fetchBookDetails(connection, "Introduction to Java");

// Closing the connection


connection.close();
System.out.println("Disconnected from the database");
} catch (SQLException e) {
e.printStackTrace();
}
}

// Method to add a book to the database


static void addBook(Connection connection, String title, String author, String publisher) throws
SQLException {
String sql = "INSERT INTO books (title, author, publisher) VALUES (?, ?, ?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, title);
statement.setString(2, author);
statement.setString(3, publisher);
int rowsAffected = statement.executeUpdate();
if (rowsAffected > 0) {
System.out.println("Book added successfully");
} else {
System.out.println("Failed to add book");
}
}

// Method to fetch details of a book including author information


static void fetchBookDetails(Connection connection, String title) throws SQLException {
String sql = "SELECT * FROM books WHERE title = ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, title);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
String bookTitle = resultSet.getString("title");
String author = resultSet.getString("author");
String publisher = resultSet.getString("publisher");
System.out.println("Title: " + bookTitle);
System.out.println("Author: " + author);
System.out.println("Publisher: " + publisher);
} else {
System.out.println("Book not found");
}
}
}
20. An Admin of a Car selling company to add and view Car information details as per the
design specifications. The data received from the user (Admin) will be stored in
database and retrieved when required. Create required database and tables, to insert
records into tables using JDBC application Program.

CREATE DATABASE car_selling_company;


USE car_selling_company;
CREATE TABLE Cars (
CarID INT AUTO_INCREMENT PRIMARY KEY,
Brand VARCHAR(255) NOT NULL,
Model VARCHAR(255) NOT NULL,
Year INT NOT NULL,
Price DECIMAL(10, 2) NOT NULL
);

import java.sql.*;

public class CarSellingCompany {


public static void main(String[] args) {
// JDBC Connection variables
String url = "jdbc:mysql://localhost:3306/car_selling_company"; // Database URL
String username = "your_username";
String password = "your_password";

try {
// Load the MySQL JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Create a connection to the database


Connection connection = DriverManager.getConnection(url, username, password);

// Inserting records into the Cars table


insertCar(connection, "Toyota", "Camry", 2022, 25000.00);
insertCar(connection, "Honda", "Civic", 2023, 22000.00);
insertCar(connection, "Ford", "Mustang", 2021, 35000.00);

// Retrieving and displaying car information from the Cars table


displayCars(connection);

// Close the connection


connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// Method to insert a car record into the Cars table
public static void insertCar(Connection connection, String brand, String model, int year, double
price) throws SQLException {
String sql = "INSERT INTO Cars (Brand, Model, Year, Price) VALUES (?, ?, ?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, brand);
preparedStatement.setString(2, model);
preparedStatement.setInt(3, year);
preparedStatement.setDouble(4, price);
int rowsInserted = preparedStatement.executeUpdate();
if (rowsInserted > 0) {
System.out.println("A new car record was inserted successfully.");
}
preparedStatement.close();
}

// Method to retrieve and display all car records from the Cars table
public static void displayCars(Connection connection) throws SQLException {
String sql = "SELECT * FROM Cars";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
int carID = resultSet.getInt("CarID");
String brand = resultSet.getString("Brand");
String model = resultSet.getString("Model");
int year = resultSet.getInt("Year");
double price = resultSet.getDouble("Price");
System.out.println("Car ID: " + carID + ", Brand: " + brand + ", Model: " + model + ", Year: "
+ year + ", Price: " + price);
}
resultSet.close();
statement.close();
}
}

21. Compare between JSP and Servlet?

Servlet JSP

Servlet is a java code. JSP is a HTML-based compilation code.

Writing code for servlet is harder than JSP is easy to code as it is java in
JSP as it is HTML in java. HTML.

Servlet plays a controller role in JSP is the view in the MVC approach for
the ,MVC approach. showing output.

JSP is slower than Servlet because the


first step in the JSP lifecycle is the
Servlet is faster than JSP.
translation of JSP to java code and then
compile.

Servlet can accept all protocol requests. JSP only accepts HTTP requests.

In Servlet, we can override the service() In JSP, we cannot override its service()
method. method.

In Servlet by default session


In JSP session management is
management is not enabled, user have to
automatically enabled.
enable it explicitly.

In Servlet we have to implement In JSP business logic is separated from


everything like business logic and presentation logic by using
presentation logic in just one servlet file. JavaBeansclient-side.

Modification in Servlet is a time-


consuming compiling task because it JSP modification is fast, just need to
includes reloading, recompiling, click the refresh button.
JavaBeans and restarting the server.
Servlet JSP

It does not have inbuilt implicit objects. In JSP there are inbuilt implicit objects.

While running the JavaScript at the


There is no method for running
client side in JSP, client-side validation
JavaScript on the client side in Servlet.
is used.

Packages can be imported into the JSP


Packages are to be imported on the top
program (i.e, bottom , middleclient-side,
of the program.
or top )

It cannot handle extensive data


It can handle extensive data processing.
processing very efficiently.

The facility of writing custom tags is not The facility of writing custom tags is
present. present.

Before the execution, JSP is compiled in


Servlets are hosted and executed on Web
Java Servlets and then it has a similar
Servers.
lifecycle as Servlets.

22. Explain about various JSP Implicit Objects


JSP (JavaServer Pages) Implicit Objects are predefined objects that are automatically
available to JSP pages without needing to be explicitly declared or instantiated. These objects
provide convenient access to various components of the JSP environment, such as request,
response, session, application, and more. Implicit objects in JSP are accessible throughout the
entire JSP page.

Here are the various implicit objects available in JSP:

request: This object represents the client's request to the server and provides access to
parameters sent by the client in the request. It allows JSP pages to retrieve form data, query
parameters, and other information sent by the client.

response: This object represents the server's response to the client and provides methods to
set response headers, status codes, and send content back to the client. It allows JSP pages to
generate dynamic content to be sent back to the client.

out: This object represents the output stream used to send content to the client. It is typically
used to write HTML content or other text-based data that will be included in the response sent
to the client.
session: This object represents the user's session and provides access to session attributes,
which are objects stored on the server and associated with the user's session. It allows JSP
pages to store and retrieve user-specific data across multiple requests.

application: This object represents the servlet context or application context and provides
access to application-wide resources and configuration parameters. It allows JSP pages to
share data and resources across all users and sessions within the web application.

config: This object represents the configuration of the JSP page and provides access to
initialization parameters specified in the web deployment descriptor (web.xml). It allows JSP
pages to retrieve configuration settings specific to the current JSP page.

page: This object represents the current JSP page itself and provides access to various
attributes and methods related to the JSP page's execution environment. It allows JSP pages to
perform operations such as forwarding requests, including other resources, and accessing
page-scoped attributes.

pageContext: This object represents the page context and provides access to all the other
implicit objects, as well as methods for managing page scope, request scope, session scope,
and application scope attributes. It serves as a bridge between JSP pages and the underlying
servlet environment.

23. Develop a servlet code to illustrate the usage of getParameterValues() method of


HTTPServletRequest object.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ParameterValuesServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
// Retrieve parameter values sent from the client
String[] hobbies = request.getParameterValues("hobby");
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Parameter Values Example</title>");
out.println("</head>");
out.println("<body>");
out.println("<h2>Selected Hobbies:</h2>");
out.println("<ul>");
if (hobbies != null) {
// Display each selected hobby
for (String hobby : hobbies) {
out.println("<li>" + hobby + "</li>");
}
} else {
out.println("<li>No hobbies selected</li>");
}
out.println("</ul>");
out.println("</body>");
out.println("</html>");
}
}

24. Assume Products table in oracle database with following fields ( PID, Pname,
Manufacturer, Price) a) Create a HTML form that prompts the user to select a
Manufacturer Name from a Drop down list along with submit Button. b) Build Servlet
code to display all the products manufactured by the manufacturer selected by the user
through HTML form.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Select Manufacturer</title>
</head>
<body>
<h2>Select Manufacturer</h2>
<form action="DisplayProductsServlet" method="post">
<label for="manufacturer">Select Manufacturer:</label>
<select id="manufacturer" name="manufacturer">
<option value="Manufacturer A">Manufacturer A</option>
<option value="Manufacturer B">Manufacturer B</option>
<option value="Manufacturer C">Manufacturer C</option>
<!-- Add more manufacturer options as needed -->
</select><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
DisplayProductsServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.sql.*;

@WebServlet("/DisplayProductsServlet")
public class DisplayProductsServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

// Retrieve selected manufacturer from the form


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

// JDBC Connection variables


String url = "jdbc:oracle:thin:@localhost:1521:XE"; // Oracle database URL
String username = "your_username";
String password = "your_password";

// SQL query to select products by manufacturer


String sql = "SELECT * FROM Products WHERE Manufacturer = ?";
// Establish database connection
try {
Class.forName("oracle.jdbc.driver.OracleDriver"); // Load Oracle JDBC driver
Connection conn = DriverManager.getConnection(url, username, password);

// Create PreparedStatement to execute SQL query


PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, manufacturer);

// Execute the query


ResultSet rs = pstmt.executeQuery();

// Display product details


out.println("<h2>Products Manufactured by " + manufacturer + ":</h2>");
out.println("<ul>");
while (rs.next()) {
out.println("<li>" + rs.getString("Pname") + " - " + rs.getString("Price") + "</li>");
}
out.println("</ul>");

// Close ResultSet, PreparedStatement, and Connection


rs.close();
pstmt.close();
conn.close();

} catch (Exception e) {
out.println("<p>Error: " + e.getMessage() + "</p>");
}
}
}
25. Describe the steps to establish a connection to a database using JDBC.
There are 5 steps to connect any java application with the database using JDBC.
These steps are as follows:
o Register the Driver class
o Create connection
o Create statement
o Execute queries
o Close connection

1) Register the driver class


The forName() method of Class class is used to register the driver class. This method is used to
dynamically load the driver class.
Syntax of forName() method
public static void forName(String className)throws ClassNotFoundException
Note: Since JDBC 4.0, explicitly registering the driver is optional. We just need to put vender's Jar in
the classpath, and then JDBC driver manager can detect and load the driver automatically.
Example to register the OracleDriver class
Here, Java program is loading oracle driver to esteblish database connection.
Class.forName("oracle.jdbc.driver.OracleDriver");
2) Create the connection object
The getConnection() method of DriverManager class is used to establish connection with the
database.
Syntax of getConnection() method
1) public static Connection getConnection(String url)throws SQLException
2) public static Connection getConnection(String url,String name,String password)
throws SQLException
Example to establish connection with the Oracle database
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","password");
3) Create the Statement object
The createStatement() method of Connection interface is used to create statement. The object of
statement is responsible to execute queries with the database.
Syntax of createStatement() method
public Statement createStatement()throws SQLException
Example to create the statement object
Statement stmt=con.createStatement();
4) Execute the query
The executeQuery() method of Statement interface is used to execute queries to the database. This
method returns the object of ResultSet that can be used to get all the records of a table.
Syntax of executeQuery() method
public ResultSet executeQuery(String sql)throws SQLException
Example to execute query
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
5) Close the connection object
By closing connection object statement and ResultSet will be closed automatically. The close()
method of Connection interface is used to close the connection.
Syntax of close() method
public void close()throws SQLException
Example to close connection
con.close();

26. Explain the usage of basic DDL and DML statements in SQL
In SQL (Structured Query Language), DDL (Data Definition Language) and DML (Data
Manipulation Language) statements are used to define, modify, and manipulate the structure
and data of databases. Here's a brief explanation of their usage:

DDL (Data Definition Language):

DDL statements are used to define and manage the structure of database objects such as
tables, indexes, views, and schemas.
Common DDL statements include:
CREATE: Used to create new database objects such as tables, indexes, or views. For
example, CREATE TABLE, CREATE INDEX.
ALTER: Used to modify the structure of existing database objects. For example, ALTER
TABLE, ALTER INDEX.
DROP: Used to delete existing database objects. For example, DROP TABLE, DROP
INDEX.
TRUNCATE: Used to remove all records from a table, but keep the table structure intact.
RENAME: Used to rename an existing database object. For example, RENAME TABLE.
Example:
CREATE TABLE Employees (
EmpID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Age INT
);
DML (Data Manipulation Language):

DML statements are used to manipulate the data stored in database objects such as tables.
Common DML statements include:
SELECT: Used to retrieve data from one or more tables. It is not strictly a DML statement
but is commonly categorized as such.
INSERT: Used to add new records to a table. For example, INSERT INTO.
UPDATE: Used to modify existing records in a table. For example, UPDATE.
DELETE: Used to remove records from a table. For example, DELETE FROM.
Example:
INSERT INTO Employees (EmpID, FirstName, LastName, Age)
VALUES (1, 'John', 'Doe', 30);

27. Differentiate between Statement, PreparedStatement, and CallableStatement.

28. Demonstrate JDBC program to display STUDENT table.


import java.sql.*;

public class DisplayStudentTable {


public static void main(String[] args) {
// JDBC Connection variables
String url = "jdbc:mysql://localhost:3306/mydatabase"; // Database URL
String username = "your_username";
String password = "your_password";

// SQL query to select all records from the STUDENT table


String sql = "SELECT * FROM STUDENT";

// Establish database connection


try {
// Load the MySQL JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Create a connection to the database


Connection connection = DriverManager.getConnection(url, username, password);

// Create a statement for executing SQL queries


Statement statement = connection.createStatement();

// Execute the SQL query and get the result set


ResultSet resultSet = statement.executeQuery(sql);

// Process the result set and display records


System.out.println("Student Table:");
System.out.println("ID\tName\t\tAge\tGrade");
while (resultSet.next()) {
int id = resultSet.getInt("ID");
String name = resultSet.getString("Name");
int age = resultSet.getInt("Age");
String grade = resultSet.getString("Grade");
System.out.println(id + "\t" + name + "\t\t" + age + "\t" + grade);
}

// Close the result set, statement, and connection


resultSet.close();
statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

29. Develop SQL Statements for the following tables using suitable datatypes and
constraints as specified below in ORACLE database Department(DeptID, DName) ;
Primary Key : DeptID ,Course (CourseID, CourseName,Credits) ; Primary Key :
CourseID ,Regsitration(StudentID, CourseCode,BranchID);Primary Key : StudentID
Foreign key(s):CourseCode Course(CourseID), BranchID Department(DeptID) .Write
sql queries for the following 1.Display all courses registered by a student along with
course name and credits 2.Display all students of “IoT" branch
-- Department table
CREATE TABLE Department (
DeptID INT PRIMARY KEY,
DName VARCHAR(100)
);

-- Course table
CREATE TABLE Course (
CourseID INT PRIMARY KEY,
CourseName VARCHAR(100),
Credits INT
);

-- Registration table
CREATE TABLE Registration (
StudentID INT,
CourseCode INT,
BranchID INT,
PRIMARY KEY (StudentID),
FOREIGN KEY (CourseCode) REFERENCES Course(CourseID),
FOREIGN KEY (BranchID) REFERENCES Department(DeptID)
);
Display all courses registered by a student along with course name and credits:
SELECT R.StudentID, C.CourseName, C.Credits
FROM Registration R
JOIN Course C ON R.CourseCode = C.CourseID
WHERE R.StudentID = <student_id>;

Display all students of “IoT" branch:


SELECT R.StudentID
FROM Registration R
JOIN Department D ON R.BranchID = D.DeptID
WHERE D.DName = 'IoT';
30. Assume a table Employees with following fields (Empid, FirstName, LastName,
Department) in ORACLE database. Write SQL statements to create the above table and
• Insert 4 records into the above table • Display the Last Name of all employees. • Select
all the data of employees whose FirstName is "Smith" or "Doe". • Update the Lastname
of Employee 7788 as “Kluever”. • Delete the record(s) of employee 7654. • Display all the
employees who work in department 30.

CREATE TABLE Employees (


Empid INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Department VARCHAR(50)
);

INSERT INTO Employees (Empid, FirstName, LastName, Department)


VALUES (7369, 'John', 'Smith', 'IT');

INSERT INTO Employees (Empid, FirstName, LastName, Department)


VALUES (7499, 'Adam', 'Doe', 'HR');

INSERT INTO Employees (Empid, FirstName, LastName, Department)


VALUES (7521, 'Mary', 'Smith', 'Finance');

INSERT INTO Employees (Empid, FirstName, LastName, Department)


VALUES (7788, 'Chris', 'Jones', 'IT');
Display Last Names of all Employees:
SELECT LastName FROM Employees;
Select Data of Employees whose FirstName is "Smith" or "Doe":
SELECT * FROM Employees WHERE FirstName IN ('Smith', 'Doe');
Update Last Name of Employee 7788 to "Kluever":
UPDATE Employees SET LastName = 'Kluever' WHERE Empid = 7788;
Delete Record(s) of Employee 7654:
DELETE FROM Employees WHERE Empid = 7654;
Display all Employees who work in department 30:
SELECT * FROM Employees WHERE Department = '30';

31. Explain the translation phase and request processing phase involved in processing a JSP
page by a web server
When a JSP (JavaServer Pages) page is requested by a client, it goes through two main phases in the
web server: the translation phase and the request processing phase.

Translation Phase:

In the translation phase, the JSP container translates the JSP page into a servlet class.
The translation process involves the following steps:
Parsing: The JSP container parses the JSP page to identify static content (HTML markup) and
dynamic content (Java code embedded within <% %> tags).
Compilation: The JSP container compiles the parsed JSP page into a Java servlet class.
Class Generation: The container generates a Java servlet class from the compiled JSP page. This
servlet class extends the HttpServlet class and overrides the doGet() or doPost() method to process
HTTP requests.
Compilation Errors Handling: If there are any compilation errors in the JSP page, the container
reports them to the developer for correction.
Request Processing Phase:

In the request processing phase, the servlet container executes the generated servlet class to process
the client's request.
The request processing phase involves the following steps:
Instantiation: The servlet container instantiates an object of the generated servlet class to handle the
client's request.
Initialization: The container calls the init() method of the servlet to perform any initialization tasks.
This method is called only once during the servlet's lifecycle.
Service Method Invocation: The container calls the service() method of the servlet, passing the HTTP
request and response objects as parameters. Depending on the type of HTTP request (GET, POST,
etc.), the service() method dispatches the request to the appropriate doGet(), doPost(), or other
methods defined in the servlet.
Response Generation: The servlet processes the client's request, generates dynamic content (if any),
and sends the response back to the client via the HttpServletResponse object.
Destruction: After serving the request, the container calls the destroy() method of the servlet to
perform any cleanup tasks. This method is called only once during the servlet's lifecycle, typically
when the servlet container shuts down or reloads the application.
32. Identify the methods involved in Servlet Life Cycle and explain their usage.
The Servlet API defines several methods that are involved in the lifecycle of a servlet. These
methods are called by the servlet container at various stages of the servlet's lifecycle. Below
are the main methods involved in the servlet lifecycle and their usage:

init():

The init() method is called by the servlet container when the servlet is first initialized.
This method is typically used to perform one-time initialization tasks, such as loading
configuration data or establishing database connections.
The init() method is called only once during the lifecycle of a servlet, immediately after the
servlet is instantiated.
service():

The service() method is called by the servlet container to handle client requests.
This method receives HttpServletRequest and HttpServletResponse objects as parameters,
representing the client's request and the response to be sent back to the client.
The service() method determines the type of HTTP request (GET, POST, etc.) and dispatches
the request to the appropriate doGet(), doPost(), or other methods defined in the servlet.
doGet() / doPost() / doPut() / doDelete(), etc.:

These are the HTTP-specific methods called by the service() method to handle different types
of HTTP requests (GET, POST, PUT, DELETE, etc.).
Servlets override these methods to provide custom request handling logic for each type of
HTTP request.
For example, the doGet() method is called to handle HTTP GET requests, while the doPost()
method is called to handle HTTP POST requests.
destroy():

The destroy() method is called by the servlet container when the servlet is about to be
unloaded or taken out of service.
This method is typically used to perform cleanup tasks, such as releasing database
connections or closing resources.
The destroy() method is called only once during the lifecycle of a servlet, immediately before
the servlet is destroyed.

33. Develop Servlet code to validate the Credit Card Expiration Year selected by the user
through HTML form. If valid then display a message “Valid Card” else “ Card Expired
“ . (Assume the Card Expiration Year is 2027)
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("/ValidateCreditCardServlet")
public class ValidateCreditCardServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
// Get the credit card expiration year selected by the user from the HTML form
String expirationYearStr = request.getParameter("expirationYear");
// Assume the card expiration year is 2027
int currentYear = 2027;
try {
// Parse the expiration year to an integer
int expirationYear = Integer.parseInt(expirationYearStr);
// Validate the credit card expiration year
if (expirationYear >= currentYear) {
out.println("<html><body>");
out.println("<h2>Valid Card</h2>");
out.println("</body></html>");
} else {
out.println("<html><body>");
out.println("<h2>Card Expired</h2>");
out.println("</body></html>");
}
} catch (NumberFormatException e) {
out.println("<html><body>");
out.println("<h2>Invalid Year</h2>");
out.println("</body></html>");
}
}
}
34. Build JSP code to validate the mobile number entered by the user. A VALID mobile
number has exactly 10 digits. If the mobile number is valid display the message “
Thanks for providing your contact number” else display the message “ Invalid Mobile
Number”.

<!DOCTYPE html>
<html>
<head>
<title>Mobile Number Validation</title>
<script>
function validateMobileNumber() {
var mobileNumber = document.getElementById("mobileNumber").value;
// Regular expression to match exactly 10 digits
var regex = /^\d{10}$/;
if (regex.test(mobileNumber)) {
document.getElementById("message").innerHTML = "Thanks for providing your
contact number";
return true; // Valid mobile number
} else {
document.getElementById("message").innerHTML = "Invalid Mobile Number";
return false; // Invalid mobile number
}
}
</script>
</head>
<body>
<h2>Mobile Number Validation</h2>
<form onsubmit="return validateMobileNumber()">
<label for="mobileNumber">Enter Mobile Number:</label>
<input type="text" id="mobileNumber" name="mobileNumber">
<input type="submit" value="Submit">
</form>
<p id="message"></p>
</body>
</html>

You might also like