AJP PAST PAPER SOLUTIONS
SUMMER 2023
Q.1 (a) Demonstrate the use of ResultSetMetadata.
Ans:- First, what is ResultSetMetaData?
It’s an interface in java.sql that lets you find out information about the columns of a
ResultSet, like:
Number of columns
Column names
Column types
Column display size, etc.
✨ Simple Example: Using ResultSetMetaData
import java.sql.*;
public class ResultSetMetadataDemo {
public static void main(String[] args) {
// Database connection details
String url = "jdbc:mysql://localhost:3306/sampledb"; // Replace with your DB URL
String user = "root"; // Replace with your DB username
String password = "password"; // Replace with your DB password
try (
// Connect to database
Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT id, name, email FROM users"); // Sample
table
){
// Get metadata from ResultSet
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
System.out.println("Number of columns: " + columnCount);
// Print details of each column
for (int i = 1; i <= columnCount; i++) {
System.out.println("Column " + i + ":");
System.out.println(" Name: " + rsmd.getColumnName(i));
System.out.println(" Type: " + rsmd.getColumnTypeName(i));
System.out.println(" Display Size: " + rsmd.getColumnDisplaySize(i));
System.out.println();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
🛠 What this program does:
Connects to a database (you can adjust URL, user, password).
Runs a query (SELECT id, name, email FROM users).
Uses ResultSetMetaData to fetch:
o Total number of columns
o For each column: Name, Type, and Display Size.
Prints the information.
🧠 Some Useful ResultSetMetaData Methods:
Method What it does
getColumnCount() Total number of columns
getColumnName(int column) Column name
getColumnTypeName(int column) SQL data type name (e.g., VARCHAR)
getColumnDisplaySize(int column) Maximum width of the column
isNullable(int column) Whether the column can be NULL
isAutoIncrement(int column) Whether the column is auto-incremented
(b) Implement the client server program using UDP Sockets. Client will request to download
the file from server and server will send it to client.
Ans:- I'll show you a simple UDP client-server program where:
Client sends a request for a file (by filename).
Server reads the file and sends its content over UDP packets to the client.
Since UDP is connectionless and unreliable, this will be a basic version without reliability
checks (no retransmissions, etc.).
📜 1. Server Code (UDP File Sender)
import java.net.*;
import java.io.*;
public class UDPFileServer {
public static void main(String[] args) {
final int PORT = 9876;
try (DatagramSocket serverSocket = new DatagramSocket(PORT)) {
byte[] receiveBuffer = new byte[1024];
byte[] sendBuffer;
System.out.println("Server is running and waiting for client...");
// Receive filename from client
DatagramPacket receivePacket = new DatagramPacket(receiveBuffer,
receiveBuffer.length);
serverSocket.receive(receivePacket);
String fileName = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("Client requested file: " + fileName);
InetAddress clientAddress = receivePacket.getAddress();
int clientPort = receivePacket.getPort();
File file = new File(fileName);
if (!file.exists()) {
String errorMessage = "File not found";
sendBuffer = errorMessage.getBytes();
serverSocket.send(new DatagramPacket(sendBuffer, sendBuffer.length,
clientAddress, clientPort));
} else {
FileInputStream fis = new FileInputStream(file);
int bytesRead;
while ((bytesRead = fis.read(receiveBuffer)) != -1) {
DatagramPacket sendPacket = new DatagramPacket(receiveBuffer, bytesRead,
clientAddress, clientPort);
serverSocket.send(sendPacket);
Thread.sleep(10); // small delay to avoid packet loss
}
// Send end of file signal
String doneMessage = "EOF";
sendBuffer = doneMessage.getBytes();
serverSocket.send(new DatagramPacket(sendBuffer, sendBuffer.length,
clientAddress, clientPort));
fis.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
📜 2. Client Code (UDP File Receiver)
import java.net.*;
import java.io.*;
public class UDPFileClient {
public static void main(String[] args) {
final String SERVER_IP = "localhost"; // or IP address of server
final int SERVER_PORT = 9876;
final String OUTPUT_FILE = "received_file.txt";
try (DatagramSocket clientSocket = new DatagramSocket();
FileOutputStream fos = new FileOutputStream(OUTPUT_FILE)) {
BufferedReader userInput = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter the filename to download: ");
String fileName = userInput.readLine();
// Send filename to server
byte[] sendBuffer = fileName.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendBuffer, sendBuffer.length,
InetAddress.getByName(SERVER_IP), SERVER_PORT);
clientSocket.send(sendPacket);
byte[] receiveBuffer = new byte[1024];
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveBuffer,
receiveBuffer.length);
clientSocket.receive(receivePacket);
String receivedData = new String(receivePacket.getData(), 0,
receivePacket.getLength());
if (receivedData.equals("File not found")) {
System.out.println("Server says: File not found.");
break;
} else if (receivedData.equals("EOF")) {
System.out.println("File received successfully.");
break;
} else {
fos.write(receivePacket.getData(), 0, receivePacket.getLength());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
🛠 How It Works:
Client Side Server Side
Sends filename to server Receives filename
Waits to receive file content packets Reads file and sends packets
Writes received data into a file Sends "EOF" after file completion
📦 Important Notes:
UDP does not guarantee delivery, order, or integrity!
(This is a simple example without reliability mechanisms.)
For larger real-world file transfer, TCP is better, or you’d have to implement reliability
at the application layer.
I added a slight Thread.sleep(10) at server after sending packets — it helps avoid
packet overflow on fast systems.
(c) What do you mean by session tracking? Discuss different session tracking.
Ans:- What is Session Tracking?
In web applications, HTTP is stateless, meaning each request is independent — the server
does not remember if two requests came from the same client.
Session Tracking is a technique used to maintain state (or remember information) about a
user across multiple HTTP requests.
Example: When you log into a website and move between pages, you stay logged in — that's
session tracking!
🎯 Why do we need session tracking?
To remember user login information.
To store items in a shopping cart.
To track user activity (like page visits).
To manage user-specific settings during interaction.
Different Session Tracking Techniques:
Method How it Works Pros Cons
Small text files stored in
Easy to use, Users can disable
browser. Server sends cookie,
1. Cookies automatic cookies. Limited size
browser returns it with every
browser handling. (4KB).
request.
No need for URLs become long and
Session ID is added to the URL cookies. Works ugly. Users can
2. URL Rewriting
as a parameter. even if cookies copy/share session links
are disabled. (security risk).
Hidden input fields inside Works without Works only for form
3. Hidden Form
HTML forms store session cookies. Good for submissions (POST
Fields
data. multi-page forms. requests).
Server creates a session object
Secure (data not
4. HttpSession for each client and stores data
in browser). Needs memory
(Server-side on server-side. A session ID is
Scalable and management on server.
sessions) passed (via cookie or URL
flexible.
rewriting).
✨ Quick Explanation of Each:
1. Cookies
Server sends a Set-Cookie header.
Browser stores it and sends it back automatically with every future request.
// Setting cookie (Servlet Example)
Cookie cookie = new Cookie("username", "John");
response.addCookie(cookie);
2. URL Rewriting
Add session data to every URL manually.
Example:
http://example.com/page?sessionId=12345
// Encoding URL (Servlet Example)
String encodedURL = response.encodeURL("page.jsp");
3. Hidden Form Fields
Include session ID inside a hidden form field in the webpage.
<form action="nextPage.jsp">
<input type="hidden" name="sessionId" value="12345">
<input type="submit" value="Next">
</form>
4. HttpSession (Best practice)
Server creates a HttpSession object.
Stores information like login status, cart items, preferences.
// Creating a session (Servlet Example)
HttpSession session = request.getSession();
session.setAttribute("username", "John");
🧠 Conclusion:
Small websites can use cookies or URL rewriting.
Large or secure applications should use HttpSession with cookies (or fallback to URL
rewriting if cookies are disabled).
Hidden fields are useful mainly for form-based flows.
Q.2 (a) Compare ServerSocket with Socket.
Ans:-
Feature ServerSocket Socket
Listens for incoming client
Purpose Connects to a server (client side).
connections (server side).
Acts like a doorbell - waits for Acts like a phone - initiates/maintains
Main Role
clients to connect. communication.
Important accept() — waits and accepts a getInputStream(), getOutputStream() —
Methods client connection. to send/receive data.
Client side (or also server-side after
Side Used Server side
accept)
ServerSocket server = new Socket client = new Socket("localhost",
Example
ServerSocket(5000); 5000);
(b) Differentiate ServletConfig and ServletContext.
Ans:-
Feature ServletConfig ServletContext
Scope Specific to one servlet. Shared by all servlets in a web app.
Purpose Provides init parameters for a servlet. Provides application-level information.
Created when web application is
Creation Created when a servlet is initialized.
deployed.
Example Fetch servlet-specific settings like email id, Fetch global settings like database
Use admin name, etc. URL, log directory.
Example
config.getInitParameter("adminEmail"); context.getInitParameter("dbURL");
Code
(c) Demonstrate the use of ServletRequestDispacher and its methods include and forward.
Ans:- ServletRequestDispatcher is used to transfer control from one servlet (or JSP) to
another within the same server.
🧩 Code Example:
java
CopyEdit
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h3>First Servlet</h3>");
// Forward example
String action = request.getParameter("action");
RequestDispatcher rd;
if ("forward".equals(action)) {
rd = request.getRequestDispatcher("SecondServlet");
rd.forward(request, response); // Transfers control
} else {
rd = request.getRequestDispatcher("SecondServlet");
rd.include(request, response); // Includes SecondServlet output here
}
out.println("<h3>Back to First Servlet</h3>");
}
}
java
CopyEdit
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
IOException {
PrintWriter out = response.getWriter();
out.println("<h3>Inside Second Servlet</h3>");
}
}
📖 Behavior:
Method What happens
Transfers request/response to another resource and stops processing in the
forward()
current servlet.
include() Includes output of another resource and continues processing current servlet.
📌 Summary:
ServerSocket vs Socket ➔ ServerSocket accepts connections, Socket connects to
server.
ServletConfig vs ServletContext ➔ ServletConfig is per servlet, ServletContext is
global for app.
ServletRequestDispatcher ➔ forward() to hand over control, include() to merge
outputs.
OR (c) Demonstrate the use of JSP action tags include and forward.
Ans:- ✨ JSP Action Tags: <jsp:include> and <jsp:forward>
In JSP, action tags are used to control the flow or include content dynamically.
Action Tag Purpose
<jsp:include> Includes another resource (JSP/HTML/Servlet) at runtime.
Forwards the request to another resource without returning to the current
<jsp:forward>
page.
📜 Example for <jsp:include>
📄 main.jsp
<html>
<body>
<h2>Main JSP Page</h2>
<!-- Including another JSP -->
<jsp:include page="header.jsp" />
<p>Welcome to the main content area!</p>
<jsp:include page="footer.jsp" />
</body>
</html>
📄 header.jsp
<h3>Welcome to My Website</h3>
<hr>
📄 footer.jsp
<hr>
<p>Contact us at [email protected]</p>
🧠 What Happens?
When you open main.jsp, it includes header.jsp and footer.jsp at runtime.
Changes made to header.jsp or footer.jsp will automatically reflect in main.jsp.
📜 Example for <jsp:forward>
📄 first.jsp
<%
String user = request.getParameter("user");
if (user == null || user.isEmpty()) {
%>
<jsp:forward page="login.jsp" />
<%
}
%>
<html>
<body>
<h2>Welcome, <%= user %>!</h2>
</body>
</html>
📄 login.jsp
<html>
<body>
<h2>Please login first!</h2>
<form action="first.jsp">
Enter Name: <input type="text" name="user">
<input type="submit" value="Login">
</form>
</body>
</html>
🧠 What Happens?
If no user name is given, first.jsp forwards the request to login.jsp.
After submitting the form, it comes back to first.jsp and shows "Welcome, [user]!".
🚀 Summary:
Action Tag Behavior
<jsp:include> Inserts another file’s content at runtime (dynamic).
<jsp:forward> Redirects the whole request to another page without returning.
Q.3 (a) Write a code snippet to show the use of PreparedStatement.
Ans:- ✨ Code Snippet: Using PreparedStatement
import java.sql.*;
public class PreparedStatementExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/sampledb"; // Database URL
String user = "root"; // Database username
String password = "password"; // Database password
try (
// Connect to database
Connection conn = DriverManager.getConnection(url, user, password);
// Create PreparedStatement
PreparedStatement pstmt = conn.prepareStatement(
"INSERT INTO users (name, email) VALUES (?, ?)"
);
){
// Set values for placeholders
pstmt.setString(1, "John Doe"); // 1st ? becomes "John Doe"
pstmt.setString(2, "[email protected]"); // 2nd ? becomes "[email protected]"
// Execute the query
int rowsInserted = pstmt.executeUpdate();
if (rowsInserted > 0) {
System.out.println("A new user was inserted successfully!");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
🛠 What's happening here?
? are placeholders in SQL.
setString(1, "John Doe") sets the first placeholder.
setString(2, "
[email protected]") sets the second placeholder.
executeUpdate() runs the query to insert data.
📋 Why use PreparedStatement?
Advantage Reason
Security Prevents SQL Injection attacks.
Efficiency Query is precompiled, faster execution.
Convenience Easy to insert/update data dynamically.
(b) What is filter? How will you configure filter using deployment descriptor?
Ans:- ✨ What is a Filter in Java EE (Servlet Filter)?
A Filter is a special Java class used to intercept requests and responses before they reach a
servlet or after they leave a servlet.
Think of it like a security guard — checking/modifying the request or response without
changing the actual servlet.
🎯 Why use Filters?
Authentication and Authorization (Login check)
Logging and auditing (who accessed what)
Compressing response (like gzip)
Modifying request/response data (add/remove headers)
🛠 Basic Structure of a Filter
A filter must implement the javax.servlet.Filter interface.
import javax.servlet.*;
import java.io.IOException;
public class MyFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
// Initialization code (if needed)
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// Pre-processing request
System.out.println("Filter is executing before servlet...");
chain.doFilter(request, response); // Pass control to next filter or servlet
// Post-processing response
System.out.println("Filter is executing after servlet...");
}
public void destroy() {
// Cleanup code (if needed)
}
}
📦 How to Configure Filter using Deployment Descriptor (web.xml)?
You need to declare the filter and map it to a servlet or URL pattern.
📄 web.xml example:
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/welcome</url-pattern>
</filter-mapping>
📖 What this does:
The filter named MyFilter will apply to the servlet or URL pattern /welcome.
Whenever the user accesses /welcome, the MyFilter will run before and after the
servlet runs.
📌 Summary:
Aspect Explanation
Filter Java class that can intercept requests/responses.
Purpose Security, logging, compression, etc.
Configuration Done via web.xml using <filter> and <filter-mapping> tags.
(c) Develop a web application as following to demonstrate the use of <jsp:useBean>
1) Create a Java Bean named Student with attributes name and age.
2) Create a web page to set the properties of Student using <jsp:useBean>.
3) Create a web page to display the properties of Student using <jsp:useBean>.
Ans:- Here’s a simple web application using <jsp:useBean>
🛠 1) Create a JavaBean Student.java
// Save as: Student.java
package bean;
public class Student {
private String name;
private int age;
// Default constructor
public Student() {}
// Getter and Setter for name
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// Getter and Setter for age
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
✅ Important:
JavaBean must have private fields.
Provide public getters/setters.
Must have a default (no-arg) constructor.
🛠 2) Create JSP to set properties → setStudent.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-
8"%>
<html>
<body>
<h2>Set Student Properties</h2>
<form action="showStudent.jsp" method="post">
Name: <input type="text" name="name"><br><br>
Age: <input type="text" name="age"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
✅ This page collects name and age from the user.
🛠 3) Create JSP to display properties → showStudent.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-
8"%>
<jsp:useBean id="student" class="bean.Student" scope="session" />
<jsp:setProperty name="student" property="name" param="name" />
<jsp:setProperty name="student" property="age" param="age" />
<html>
<body>
<h2>Student Details</h2>
Name: <jsp:getProperty name="student" property="name" /> <br><br>
Age: <jsp:getProperty name="student" property="age" />
</body>
</html>
✅ This page:
Creates a Student object.
Sets the properties using <jsp:setProperty>.
Displays the properties using <jsp:getProperty>.
✨ Folder Structure (Important!)
YourProject/
├── WebContent/
│ ├── setStudent.jsp
│ ├── showStudent.jsp
└── src/
└── bean/
└── Student.java
✅ Also make sure you compile Student.java correctly (if not using IDEs like
Eclipse/NetBeans).
📋 Quick Summary:
Step Action
1 Create Student JavaBean class.
2 Create setStudent.jsp to input data.
3 Create showStudent.jsp to create and display the bean using <jsp:useBean>.
OR Q.3 (a) What is FilterConfig? How will you use it?
Ans:- ✨ What is FilterConfig?
FilterConfig is an interface in javax.servlet package.
It is used to provide initialization parameters and configuration information to a
Filter.
👉 Think of it like a setup guide: before your filter starts working, it can read settings from
web.xml using FilterConfig.
🎯 Why do we need FilterConfig?
To fetch init parameters (like database name, admin email, etc.).
To access the Filter's name.
To access the ServletContext (shared application data).
🛠 How to Use FilterConfig?
When you create a filter, you override its init(FilterConfig config) method.
You can use the config object to read parameters.
📄 Example:
1. web.xml configuration:
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>MyFilter</filter-class>
<init-param>
<param-name>adminName</param-name>
<param-value>John Doe</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/dashboard</url-pattern>
</filter-mapping>
2. Java Filter class:
import javax.servlet.*;
import java.io.IOException;
public class MyFilter implements Filter {
private String adminName;
public void init(FilterConfig config) throws ServletException {
// Getting init parameter using FilterConfig
adminName = config.getInitParameter("adminName");
System.out.println("Filter initialized for Admin: " + adminName);
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
System.out.println("Request processed by filter for admin: " + adminName);
chain.doFilter(request, response);
}
public void destroy() {
// Cleanup code
}
}
🧠 Important Methods of FilterConfig:
Method Purpose
getFilterName() Returns the filter's name.
getInitParameter(String name) Returns the value of an initialization parameter.
getInitParameterNames() Returns an enumeration of all init parameter names.
getServletContext() Returns a reference to the ServletContext object.
📋 Quick Summary:
Feature FilterConfig Explanation
What Interface for passing configuration info to a Filter.
Why To read init parameters and access ServletContext.
Feature FilterConfig Explanation
Where Inside init(FilterConfig config) method.
(b) Write a code snippet to explain the use of CallableStatement.
Ans:- ✨ What is CallableStatement?
CallableStatement is used to call stored procedures in a database from Java.
Stored Procedures are predefined SQL programs stored in the database (like
functions).
🛠 Example: Using CallableStatement
Assume you have a stored procedure in your database:
🛢 SQL to create stored procedure:
CREATE PROCEDURE getStudentName(IN studentId INT, OUT studentName VARCHAR(50))
BEGIN
SELECT name INTO studentName FROM students WHERE id = studentId;
END;
✅ This procedure takes student ID and returns student Name.
📜 Java Code to Call This Stored Procedure:
import java.sql.*;
public class CallableStatementExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/sampledb"; // your database URL
String user = "root"; // your database user
String password = "password"; // your database password
try (
// Connect to database
Connection conn = DriverManager.getConnection(url, user, password);
// Prepare callable statement
CallableStatement stmt = conn.prepareCall("{call getStudentName(?, ?)}");
){
// Set the input parameter
stmt.setInt(1, 101); // Assume 101 is a student ID
// Register the output parameter
stmt.registerOutParameter(2, Types.VARCHAR);
// Execute the callable statement
stmt.execute();
// Retrieve the output value
String name = stmt.getString(2);
System.out.println("Student Name: " + name);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
🧠 Key Points:
Step Action
setInt(1, 101) Set input parameter (student ID)
registerOutParameter(2, Types.VARCHAR) Tell JDBC that 2nd parameter is an output
Step Action
execute() Run the stored procedure
getString(2) Get output value from the second parameter
📋 Quick Summary:
Feature CallableStatement Explanation
What Used to call stored procedures.
Input/Output Can have input, output, or both parameters.
Use setXXX(), registerOutParameter(), execute(), getXXX()
(c) Develop a web application as following using JSP.
1) Create a web page (HTML) to submit the registration detail (Name, email and contact
number) of user to jsp page.
2) Create a jsp page to enter the registration detail in the table of database.
3) Create a jsp page to display the list of all registered users.
Ans:- 1) Create an HTML page (registration.html)
This page will collect user details like Name, Email, and Contact Number and send them to a
JSP page.
<!-- registration.html -->
<!DOCTYPE html>
<html>
<head>
<title>User Registration</title>
</head>
<body>
<h2>User Registration</h2>
<form action="register.jsp" method="post">
<label for="name">Name:</label>
<input type="text" name="name" required><br><br>
<label for="email">Email:</label>
<input type="email" name="email" required><br><br>
<label for="contact">Contact Number:</label>
<input type="text" name="contact" required><br><br>
<input type="submit" value="Register">
</form>
</body>
</html>
2) Create the JSP page to insert registration details (register.jsp)
This JSP page will handle the form submission, validate the data, and insert it into a
database.
Steps:
1. Establish a connection to the database.
2. Insert the data into the table users.
3. Show a success or error message.
Database Structure (MySQL):
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100),
contact VARCHAR(15)
);
register.jsp:
<%@ page import="java.sql.*" %>
<%
String name = request.getParameter("name");
String email = request.getParameter("email");
String contact = request.getParameter("contact");
// Database connection details
String url = "jdbc:mysql://localhost:3306/your_database";
String user = "root";
String password = "password";
Connection conn = null;
PreparedStatement stmt = null;
try {
// Connect to the database
conn = DriverManager.getConnection(url, user, password);
// SQL Query to insert data into the database
String sql = "INSERT INTO users (name, email, contact) VALUES (?, ?, ?)";
stmt = conn.prepareStatement(sql);
// Set parameters for the PreparedStatement
stmt.setString(1, name);
stmt.setString(2, email);
stmt.setString(3, contact);
// Execute the query
int rowsInserted = stmt.executeUpdate();
if (rowsInserted > 0) {
out.println("<h3>Registration Successful!</h3>");
}
} catch (SQLException e) {
e.printStackTrace();
out.println("<h3>Error occurred while registering!</h3>");
} finally {
// Close resources
if (stmt != null) stmt.close();
if (conn != null) conn.close();
}
%>
3) Create the JSP page to display the list of registered users (listUsers.jsp)
This page will retrieve all registered users from the database and display them in a table
format.
listUsers.jsp:
<%@ page import="java.sql.*" %>
<html>
<head>
<title>Registered Users</title>
</head>
<body>
<h2>List of Registered Users</h2>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Contact</th>
</tr>
<%
// Database connection details
String url = "jdbc:mysql://localhost:3306/your_database";
String user = "root";
String password = "password";
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Connect to the database
conn = DriverManager.getConnection(url, user, password);
stmt = conn.createStatement();
// Query to fetch all users
String sql = "SELECT * FROM users";
rs = stmt.executeQuery(sql);
// Loop through the result set and display the data
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String email = rs.getString("email");
String contact = rs.getString("contact");
%>
<tr>
<td><%= id %></td>
<td><%= name %></td>
<td><%= email %></td>
<td><%= contact %></td>
</tr>
<%
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Close resources
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
%>
</table>
</body>
</html>
4) Folder Structure
Here’s how your project structure should look:
YourProject/
├── WebContent/
│ ├── registration.html <-- User Registration Form
│ ├── register.jsp <-- Insert Data to Database
│ ├── listUsers.jsp <-- Display Registered Users
└── WEB-INF/
└── web.xml <-- Web Deployment Descriptor
5) web.xml Configuration
Ensure you have your servlet mappings (though this JSP project doesn’t necessarily require
additional servlet mappings unless you have other servlets).
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<servlet>
<servlet-name>register</servlet-name>
<jsp-file>/register.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>register</servlet-name>
<url-pattern>/register.jsp</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>listUsers</servlet-name>
<jsp-file>/listUsers.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>listUsers</servlet-name>
<url-pattern>/listUsers.jsp</url-pattern>
</servlet-mapping>
</web-app>
📋 Final Overview:
Feature Explanation
registration.html A simple HTML form for user input.
register.jsp JSP page that processes the form and saves the data.
listUsers.jsp Displays all registered users in a table format.
Database Users are stored in a MySQL database (table users).
Q.4 (a) What is EL? Write a code snippet to show the use of method expressions in JSP page.
Ans:- What is EL (Expression Language)?
Expression Language (EL) is a simple language used in JSP (JavaServer Pages) to
access data from various sources such as JavaBeans, request parameters, session
attributes, or implicit objects.
EL is simpler than writing Java code directly in JSP pages, making the page more
readable and maintainable.
Key Points about EL:
EL provides access to JavaBeans, maps, arrays, lists, request parameters, session
attributes, etc.
It's used in JSP to evaluate expressions, like getting values from request, session,
application, and cookie objects, or even invoking methods.
Method Expressions in EL
You can call methods on JavaBeans or objects using method expressions in JSP. This allows
you to execute methods directly from the EL syntax.
Syntax for Method Expressions in EL:
jsp
${object.method()}
object: Can be a bean, list, map, or any object that has a method.
method(): The method that you want to invoke.
Example: Using Method Expressions in a JSP Page
Let's demonstrate this with a JavaBean and a method call using EL.
Step 1: Create a JavaBean Person.java
This Person class will have a getter method and a method that we will call using EL.
java
CopyEdit
// Person.java
package bean;
public class Person {
private String name;
private int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getter for name
public String getName() {
return name;
}
// Getter for age
public int getAge() {
return age;
}
// Method to get full details
public String getFullDetails() {
return "Name: " + name + ", Age: " + age;
}
}
Step 2: Create the JSP Page (useMethodEL.jsp)
In this JSP page, we'll set the Person bean, invoke a method using EL, and display the result.
jsp
CopyEdit
<%@ page import="bean.Person" %>
<jsp:useBean id="person" class="bean.Person" scope="session">
<jsp:setProperty name="person" property="name" value="John Doe"/>
<jsp:setProperty name="person" property="age" value="25"/>
</jsp:useBean>
<html>
<body>
<h2>Method Expression Example</h2>
<p>Full Details of Person: ${person.fullDetails()}</p>
<!-- Calls the method 'getFullDetails' of the Person bean using EL -->
<p>Name: ${person.name}</p> <!-- Accessing a simple property -->
<p>Age: ${person.age}</p> <!-- Accessing a simple property -->
</body>
</html>
Explanation of Code:
1. JSP UseBean: The <jsp:useBean> tag creates an instance of the Person class, and sets
the name and age properties using <jsp:setProperty>.
2. EL Method Expression: ${person.fullDetails()} calls the getFullDetails() method of the
Person bean using EL syntax.
3. Accessing Properties: ${person.name} and ${person.age} are used to access the
properties of the Person object.
Key EL Features in the Example:
EL method invocation: ${person.fullDetails()} calls the method getFullDetails() from
the Person bean.
EL also allows direct access to properties (${person.name}, ${person.age}) without
needing getters and setters.
📋 Summary:
Feature Description
EL Provides a simpler syntax for accessing JavaBeans, request, session, and
Feature Description
application attributes in JSP.
Method Allows calling methods on objects/beans directly from EL (e.g., $
Expressions {object.method()}).
<jsp:useBean> to create and manage JavaBean instances.
JSP Tags
<jsp:setProperty> to set properties on the bean.
This example shows how EL can simplify calling methods and accessing properties directly
without writing Java code in JSP pages.
(b) Create a custom tag to print current date and time in JSP page.
Ans:- Creating a custom tag in JSP to print the current date and time involves several steps:
1. Define the Tag Handler: The logic of the tag will be implemented in a Java class (Tag
Handler).
2. Create a Tag Library Descriptor (TLD) file: This file will map the custom tag to the tag
handler class.
3. Use the Custom Tag in JSP: Finally, use the tag in a JSP page to print the current date
and time.
Let’s go step by step.
Step 1: Create the Tag Handler Class
This Java class will define the custom tag and handle the logic to print the current date and
time.
// CurrentDateTimeTag.java
package tags;
import java.io.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CurrentDateTimeTag extends TagSupport {
@Override
public int doStartTag() throws JspException {
try {
// Create a SimpleDateFormat object to format the date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentDateTime = sdf.format(new Date());
// Output the current date and time
JspWriter out = pageContext.getOut();
out.print("Current Date and Time: " + currentDateTime);
} catch (IOException e) {
e.printStackTrace();
}
return SKIP_BODY; // No body content, tag just prints the date/time
}
}
Step 2: Create the Tag Library Descriptor (TLD)
The TLD file defines the custom tag and associates it with the tag handler class.
<!-- customTagLibrary.tld -->
<?xml version="1.0" encoding="UTF-8"?>
<taglib xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_0.xsd"
version="2.0">
<tlib-version>1.0</tlib-version>
<short-name>customTags</short-name>
<uri>http://example.com/customtags</uri>
<tag>
<name>currentDateTime</name>
<tag-class>tags.CurrentDateTimeTag</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
Step 3: Configure the TLD in web.xml
You need to declare your TLD file in the web.xml so that the JSP container can find and use
it.
<!-- web.xml -->
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<taglib>
<taglib-uri>http://example.com/customtags</taglib-uri>
<taglib-location>/WEB-INF/customTagLibrary.tld</taglib-location>
</taglib>
</web-app>
Step 4: Use the Custom Tag in a JSP Page
Now, you can use the custom tag in any JSP page.
<%@ taglib uri="http://example.com/customtags" prefix="ct" %>
<html>
<head>
<title>Current Date and Time</title>
</head>
<body>
<h2>Displaying Current Date and Time using Custom Tag:</h2>
<ct:currentDateTime />
</body>
</html>
Step 5: Directory Structure
Here’s how your project should be structured:
YourProject/
├── WebContent/
│ ├── index.jsp <-- JSP page using custom tag
├── WEB-INF/
│ ├── customTagLibrary.tld <-- Tag Library Descriptor
│ ├── lib/ <-- Required libraries (if any)
│ ├── classes/ <-- Compiled classes (tags.CurrentDateTimeTag)
│ └── web.xml <-- Web deployment descriptor
└── src/ <-- Java source files
└── tags/ <-- Java package for custom tag handler classes
└── CurrentDateTimeTag.java <-- Tag handler class
Final Thoughts:
Custom Tags in JSP are a powerful way to encapsulate reusable code logic and reduce
duplication in your JSP pages.
In this example, we created a simple custom tag to display the current date and time
in a formatted way.
You can extend this example to create more complex tags, including those with body
content, attributes, etc.
(c) Discuss JSF request processing life cycle.
Ans:- JSF Request Processing Lifecycle
The JavaServer Faces (JSF) request processing lifecycle is a series of steps that occur in a JSF
web application every time a user sends a request to a JSF page. It provides a structured and
consistent flow for processing HTTP requests and rendering responses. The lifecycle ensures
that components, data, and events are correctly handled.
The JSF lifecycle is divided into six phases, each responsible for a specific task. These phases
are executed in a well-defined order, ensuring that the web page is properly processed and
rendered.
1. Restore View Phase
Objective: The goal of the Restore View phase is to create or restore the JSF view for
the current HTTP request. If the request is a postback (i.e., a request after submitting
a form), JSF restores the existing view state (component tree, values, etc.).
Otherwise, it creates a new view for the page.
Actions:
o If the request is a postback, JSF retrieves the view state (the tree of
components and their values) from the HTTP session.
o If the request is not a postback, JSF creates a new component tree for the
page based on the JSF page (e.g., index.xhtml).
Example: When a user navigates to a page or submits a form, the view of the page is
restored based on the context.
2. Apply Request Values Phase
Objective: This phase is responsible for decoding the request parameters and
applying them to the corresponding UI components on the page.
Actions:
o JSF takes the request parameters (e.g., form fields, query parameters) and
updates the corresponding UI components (like text fields, checkboxes, etc.).
o For each UI component on the page, JSF checks if the request contains data
for it and updates its value accordingly. It may also convert the data types if
necessary.
Example: If the user enters their name in a text box, this phase ensures that the text
box component gets the value "John Doe."
3. Process Validations Phase
Objective: The Process Validations phase ensures that the input data (e.g., from
form fields) is valid according to the specified validation rules.
Actions:
o JSF validates each UI component that has validation constraints (like
@NotNull, @Size, etc.).
o If any validation error occurs, the component is marked as invalid, and JSF will
skip the remaining phases.
o Validation errors are usually displayed as error messages next to the
component.
Example: If a user enters an invalid email address, JSF validates it and generates an
error message.
4. Update Model Values Phase
Objective: The Update Model Values phase updates the backing beans with the
validated data from the UI components.
Actions:
o After validation, if the data is valid, JSF updates the values in the managed
beans (backing beans).
o JSF automatically performs conversion (e.g., from String to Integer, Date, etc.)
to ensure that the data types in the backing beans match the input data
types.
Example: If a user enters their email in a form, the email will be updated in the
corresponding managed bean (e.g., userBean.setEmail("
[email protected]")).
5. Invoke Application Phase
Objective: The Invoke Application phase is responsible for invoking the application
logic, such as event handling or method calls.
Actions:
o JSF invokes the action methods or event listeners defined in the managed
beans (backing beans).
o If the user clicked a button, an action (such as action="#{bean.someAction}")
will be invoked, triggering the corresponding bean method.
Example: When a user clicks the "submit" button, an action method like
submitForm() in the managed bean will be invoked to handle form submission and
any further processing.
6. Render Response Phase
Objective: The Render Response phase is responsible for rendering the response to
the user by creating the final HTML output.
Actions:
o JSF renders the HTML content based on the component tree.
o The response is generated by rendering the UI components into an HTML
page and sent to the client’s browser.
o If the request was a postback (e.g., form submission), JSF uses the saved state
to render the page as it was before the form was submitted.
Example: After form submission, JSF generates the updated page (with any validation
messages, new data, etc.) and sends it back to the client’s browser.
Summary of JSF Request Lifecycle Phases
Phase Description
Restore the JSF view for the current request, either creating a new view
1. Restore View
or restoring the previous one.
2. Apply Request Decodes the request parameters and applies them to the
Values corresponding UI components.
Phase Description
3. Process Validates the input data according to the constraints specified in the UI
Validations components.
4. Update Model Updates the backing beans (managed beans) with the valid data from
Values the UI components.
5. Invoke Executes any application-specific logic or actions (such as action
Application method invocations or event handling).
Generates the final HTML output based on the component tree and
6. Render Response
sends it to the client.
JSF Lifecycle with a Practical Example
Consider a simple form submission in a JSF page (form.xhtml):
<h:form>
<h:inputText value="#{userBean.name}" />
<h:commandButton value="Submit" action="#{userBean.submit}" />
</h:form>
1. Restore View: JSF creates the view if it's a fresh request or restores it if it's a
postback.
2. Apply Request Values: The user’s name entered in the input field is applied to the
userBean.name property.
3. Process Validations: JSF validates the input (e.g., checks if the name is non-empty).
4. Update Model Values: The userBean.name is updated with the value entered in the
form.
5. Invoke Application: The userBean.submit() method is invoked when the user clicks
"Submit."
6. Render Response: The page is re-rendered with any updates or validation messages,
and sent back to the client.
Conclusion
The JSF request processing lifecycle ensures that each request is processed in a systematic
and consistent way, handling UI components, validation, model updates, and rendering the
response to the user. Understanding this lifecycle helps in debugging, optimizing, and
customizing the request processing flow in a JSF-based web application.
OR Q.4 (a) Write a code snippet to show the use of JSF action event.
Ans:- JSF Action Event Example
In JSF, an action event is typically triggered by a user action, such as clicking a button. The
action method is called when a user submits a form or clicks a command button.
Steps for Using Action Event in JSF:
1. Create a Managed Bean: Define a bean with an action method that will be invoked
when the user interacts with the page.
2. Create a JSF Page: Create a page that contains a form with a command button, which
triggers the action event.
Step 1: Create a Managed Bean (UserBean.java)
This managed bean will handle the action event triggered by the button click.
// UserBean.java
package bean;
import javax.faces.bean.ManagedBean;
@ManagedBean(name = "userBean")
public class UserBean {
private String name;
private String message;
// Getter and Setter for name
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// Getter for message
public String getMessage() {
return message;
}
// Action method to be invoked when the button is clicked
public String submitAction() {
if (name != null && !name.trim().isEmpty()) {
message = "Hello, " + name + "! Welcome to JSF!";
} else {
message = "Please enter your name.";
}
return "greeting"; // Return the navigation case (greeting.xhtml)
}
}
Step 2: Create the JSF Page (index.xhtml)
This page contains a form with a commandButton that triggers the submitAction() method
when clicked.
<!-- index.xhtml -->
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<head>
<title>JSF Action Event Example</title>
</head>
<body>
<h:form>
<h:outputLabel for="name" value="Enter your name:" />
<h:inputText id="name" value="#{userBean.name}" required="true" />
<h:commandButton value="Submit" action="#{userBean.submitAction}" />
</h:form>
<!-- Display the message after form submission -->
<h:outputText value="#{userBean.message}" rendered="#{not empty userBean.message}"
/>
</body>
</html>
Step 3: Create the Navigation Page (greeting.xhtml)
After the action event is triggered, the user is navigated to a new page where the greeting
message is displayed.
<!-- greeting.xhtml -->
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<head>
<title>Greeting Page</title>
</head>
<body>
<h1>JSF Action Event Example</h1>
<h:outputText value="#{userBean.message}" />
</body>
</html>
Step 4: Faces Configuration (Optional)
If you're using JSF 2.x with annotations (as in the example), the configuration might not be
necessary. However, if needed, add the faces-config.xml to define managed beans and
navigation rules.
<!-- faces-config.xml -->
<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd">
<!-- Managed Bean Definition -->
<managed-bean>
<managed-bean-name>userBean</managed-bean-name>
<managed-bean-class>bean.UserBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
<!-- Navigation Rules -->
<navigation-rule>
<from-view-id>/index.xhtml</from-view-id>
<navigation-case>
<from-action>#{userBean.submitAction}</from-action>
<to-view-id>/greeting.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>
How It Works:
1. User Interaction: The user enters their name in the input field and clicks the Submit
button.
2. Action Event: The submitAction method in UserBean is invoked when the button is
clicked.
o The method updates the message property (userBean.message) with a
greeting based on the user's name.
3. Navigation: After the action method is invoked, JSF navigates to the greeting.xhtml
page, displaying the greeting message.
4. Output: The message is displayed in greeting.xhtml based on the result of the action
method.
JSF Flow in this Example:
1. User enters name and clicks the Submit button.
2. The submitAction method in UserBean is invoked.
3. The message property of the managed bean is updated.
4. The page navigates to greeting.xhtml, where the message is displayed.
Conclusion:
In this example, the action event is triggered by a commandButton in JSF. The action
method submitAction in the managed bean (UserBean) is invoked, which processes the
input and updates the model. The page then navigates to a new view (greeting.xhtml),
displaying the processed message.
(b) Create a JSF custom convertor and use it in JSP page.
Ans:- Creating a Custom JSF Converter and Using It in a JSP Page
A custom converter in JSF is used to convert a data type from one form to another. For
example, you might want to convert a string into a date, or a string representation of a
custom object into an actual object. A custom converter can be implemented by creating a
Java class that implements the javax.faces.convert.Converter interface.
Let's walk through how to create a custom converter and use it in a JSF page.
Step 1: Create the Custom Converter Class
In this example, we’ll create a converter that converts a string (e.g., "123") into an integer
and vice versa.
// CustomConverter.java
package converters;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
@FacesConverter("customIntegerConverter")
public class CustomConverter implements Converter {
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if (value == null || value.trim().isEmpty()) {
return null;
}
try {
// Convert string to integer
return Integer.parseInt(value);
} catch (NumberFormatException e) {
// Handle invalid number format
throw new IllegalArgumentException("Invalid integer value: " + value);
}
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (value == null) {
return "";
}
// Convert integer to string
return value.toString();
}
}
getAsObject: Converts the String value (from the user input) to an actual Integer.
getAsString: Converts the Integer value (from the model object) back to a String to
display in the input field.
The @FacesConverter annotation registers the converter with JSF, and it will be referred to
by the name "customIntegerConverter".
Step 2: Use the Custom Converter in a JSF Page
Now that we have the custom converter, we can use it in a JSF page.
<!-- index.xhtml -->
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<head>
<title>JSF Custom Converter Example</title>
</head>
<body>
<h:form>
<h:outputLabel for="age" value="Enter your age:" />
<h:inputText id="age" value="#{userBean.age}" converter="customIntegerConverter" />
<h:message for="age" style="color: red;" />
<h:commandButton value="Submit" action="#{userBean.submitAction}" />
</h:form>
<!-- Display the entered age -->
<h:outputText value="Your age is: #{userBean.age}" rendered="#{not empty
userBean.age}" />
</body>
</html>
Step 3: Create a Managed Bean to Use the Converter
We need to create a managed bean to hold the age property, which will be converted by the
custom converter.
// UserBean.java
package bean;
import javax.faces.bean.ManagedBean;
@ManagedBean
public class UserBean {
private Integer age;
// Getter and Setter for age
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
// Action method
public String submitAction() {
// For now, just return a string (you can add logic here for actual use cases)
System.out.println("Age submitted: " + age);
return null;
}
}
Step 4: Configure JSF (Optional)
If you are using JSF 2.x with managed beans and @FacesConverter annotation, you do not
need to configure it in faces-config.xml. The annotation automatically registers the custom
converter.
However, if you need to manually define managed beans, here's an optional configuration
for faces-config.xml.
<!-- faces-config.xml -->
<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd">
<managed-bean>
<managed-bean-name>userBean</managed-bean-name>
<managed-bean-class>bean.UserBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
</faces-config>
Step 5: Run the Application
1. Enter Age: When you enter an age (e.g., "25") in the input field and submit the form,
the custom converter will be used to convert the string value to an integer.
2. Display Result: After submission, the managed bean (UserBean) will hold the integer
value, and the page will render it.
How the Custom Converter Works
1. The CustomConverter is referenced in the h:inputText component using the
converter attribute:
2. converter="customIntegerConverter"
3. When the form is submitted, JSF uses the getAsObject method of the
CustomConverter to convert the string entered by the user into an integer and set it
in the UserBean property (age).
4. If the user enters an invalid integer, the getAsObject method will throw an exception,
and JSF will show a validation error message.
5. When the UserBean is rendered (via h:outputText), JSF uses the getAsString method
of the CustomConverter to convert the integer back into a string for display.
Conclusion
In this example, we created a custom JSF converter to convert a string into an integer and
vice versa. We then applied this converter to a JSF input component (h:inputText) and used
it in a managed bean to handle user input.
This approach allows you to implement custom conversion logic in a reusable way in JSF
applications.
(c) Discuss the tags of JSTL SQL tag library.
Ans:- JSTL SQL Tag Library
The JSTL SQL (JavaServer Pages Standard Tag Library) Tag Library provides tags that allow
developers to perform SQL operations directly within JSP pages. This helps to simplify
database interaction by using JSP tags instead of writing Java code. It allows for executing
queries, retrieving results, and manipulating database records with minimal boilerplate
code.
The SQL tag library in JSTL defines the following tags:
1. <sql:query>
Purpose: Executes an SQL query that returns a result set and makes the results
available for use in the JSP page.
Attributes:
o var: The name of the variable that will hold the result set.
o dataSource: A DataSource object used to obtain the database connection. If
not provided, it will use the default data source configured in the web
application.
o sql: The SQL query to be executed.
o varStatus: (Optional) A variable used to hold the status of the query
execution.
Example:
<sql:query var="result" dataSource="jdbc/myDataSource">
SELECT id, name, age FROM students
</sql:query>
<c:forEach var="student" items="${result}">
<p>${student.name} is ${student.age} years old.</p>
</c:forEach>
Explanation: This tag executes the SELECT query, stores the result set in the result
variable, and then iterates over it to display the student names and ages.
2. <sql:update>
Purpose: Executes an UPDATE, INSERT, or DELETE SQL query that does not return a
result set. It is typically used for operations that modify the database.
Attributes:
o var: The name of the variable where the number of affected rows will be
stored.
o dataSource: A DataSource object used to obtain the database connection.
o sql: The SQL query to be executed.
Example:
<sql:update var="rowsAffected" dataSource="jdbc/myDataSource">
UPDATE students SET age = age + 1 WHERE age < 20
</sql:update>
<p>${rowsAffected} rows were updated.</p>
Explanation: This tag executes an UPDATE SQL query, and the number of affected
rows is stored in the rowsAffected variable, which is then displayed on the page.
3. <sql:param>
Purpose: Provides parameters for use with <sql:query> or <sql:update> tags. It binds
parameters to placeholders (?) in the SQL query.
Attributes:
o value: The value to bind to the parameter.
o paramIndex: The position of the parameter in the SQL query (starting from 1).
Example:
<sql:query var="result" dataSource="jdbc/myDataSource">
SELECT id, name, age FROM students WHERE age > ?
<sql:param value="18" />
</sql:query>
<c:forEach var="student" items="${result}">
<p>${student.name} is ${student.age} years old.</p>
</c:forEach>
Explanation: In this example, the SELECT query contains a parameter placeholder (?).
The <sql:param> tag binds the value 18 to this placeholder, retrieving the records of
students older than 18.
4. <sql:setDataSource>
Purpose: Configures the DataSource used by the SQL tags. It can be used to configure
a DataSource from a JNDI lookup or database connection pool.
Attributes:
o var: The name of the variable where the DataSource object will be stored.
o driver: The database driver class name.
o url: The URL of the database.
o user: The database username.
o password: The database password.
o database: (Optional) The database name.
Example:
<sql:setDataSource var="myDataSource"
driver="com.mysql.cj.jdbc.Driver"
url="jdbc:mysql://localhost:3306/mydb"
user="root"
password="password" />
Explanation: This tag creates a DataSource object with the provided database
connection details and assigns it to the variable myDataSource. This DataSource can
then be used in other SQL tags (like <sql:query> and <sql:update>).
5. <sql:connection>
Purpose: Manages a database connection directly. It can be used when explicit
connection management is required (e.g., for transactions).
Attributes:
o var: The name of the variable to store the connection object.
o dataSource: The DataSource object used to obtain the connection.
Example:
<sql:connection var="conn" dataSource="jdbc/myDataSource">
<!-- Use the connection here -->
</sql:connection>
Explanation: This tag retrieves a database connection using the provided
DataSource. You can then use the connection to perform custom SQL operations.
6. <sql:rollback>
Purpose: Rolls back any database transaction that has been started. It can be used if
there is a need to revert all changes made during the current transaction.
Attributes:
o var: The name of the variable that holds the connection to be rolled back.
Example:
<sql:connection var="conn" dataSource="jdbc/myDataSource">
<!-- SQL operations here -->
</sql:connection>
<sql:rollback var="conn" />
Explanation: This tag rolls back any changes made during the current database
session using the connection specified by var.
Summary of JSTL SQL Tags
Tag Purpose
<sql:query> Executes a SQL query and stores the result set in a variable.
Executes a SQL statement (INSERT, UPDATE, DELETE) that modifies
<sql:update>
data.
<sql:param> Provides parameters for a SQL query or update.
<sql:setDataSource> Configures the DataSource object for SQL operations.
<sql:connection> Manages a database connection for custom SQL operations.
<sql:rollback> Rolls back any changes made during the current database transaction.
Advantages of Using JSTL SQL Tags:
Ease of Use: SQL operations are written declaratively with tags, reducing the need for
boilerplate JDBC code.
Clean Code: Simplifies database interaction and avoids mixing Java code with SQL
logic directly in JSP pages.
Portability: The use of DataSource objects makes it easier to switch databases, as the
configuration is externalized and not hardcoded.
Disadvantages of Using JSTL SQL Tags:
Separation of Concerns: Putting SQL operations in JSPs can lead to poor separation
of concerns, as JSPs are typically meant for presentation logic, not business logic.
Error Handling: Error handling is more complex when using JSTL SQL tags compared
to using standard JDBC with exception handling in Java classes.
Conclusion
The JSTL SQL tag library is a powerful tool for working with databases in JSP pages. It
provides simple tags for executing SQL queries, updates, and managing database
connections. However, in a production application, it's often better to keep business logic in
servlets or Java classes rather than in JSPs to maintain proper separation of concerns.
Q.5 (a) Explain the role of IoC container in Spring.
Ans:- Role of IoC Container in Spring
The Inversion of Control (IoC) container in Spring manages the lifecycle and dependencies of
beans in an application. It decouples components by handling the creation, configuration,
and wiring of objects, allowing developers to focus on business logic rather than managing
dependencies.
Key Functions:
1. Bean Creation: The IoC container creates beans from configuration files or
annotations.
2. Dependency Injection (DI): It injects dependencies into beans, reducing manual
wiring (via constructor, setter, or field injection).
3. Lifecycle Management: It manages the lifecycle of beans, including initialization and
destruction.
4. Wiring Dependencies: It automatically connects beans based on configuration.
5. Scope Management: The container manages different bean scopes (e.g., Singleton,
Prototype).
Types of IoC Containers:
BeanFactory: Basic container (used for lazy initialization).
ApplicationContext: Advanced container with more features (e.g., event
propagation, internationalization).
Example (Java-based Configuration):
@Configuration
public class AppConfig {
@Bean
public Employee employee() {
return new Employee("John", 101);
}
}
public class App {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext(AppConfig.class);
Employee emp = context.getBean(Employee.class);
emp.displayInfo();
context.close();
}
}
Benefits:
Loose Coupling: Helps decouple components.
Easier Testing: Facilitates testing by injecting mock dependencies.
Reduced Boilerplate: Minimizes repetitive code for dependency management.
In summary, the Spring IoC container simplifies the creation, management, and injection of
dependencies, improving code maintainability and testability.
(b) Explain AOP concepts of Spring.
Ans:- AOP Concepts in Spring (4 Marks)
AOP (Aspect-Oriented Programming) in Spring is a programming paradigm that allows the
separation of cross-cutting concerns (like logging, security, and transactions) from the main
business logic. This modularization makes the application more maintainable and flexible.
Core Concepts of AOP:
1. Aspect:
o A modularized cross-cutting concern (e.g., logging, security) that can be
applied to multiple parts of the application. It contains advice (code to be
executed) and pointcuts (conditions when the advice is applied).
2. Join Point:
o A specific point in the execution of the program where an aspect can be
applied. In Spring AOP, it typically refers to method execution.
3. Advice:
o The actual action to be taken at a join point. Types of advice:
Before: Executes before the method.
After: Executes after the method.
Around: Surrounds the method, allowing for control over its
execution.
4. Pointcut:
o A predicate that matches specific join points (methods). It determines where
the advice will be applied.
5. Weaving:
o The process of applying aspects to the target objects. In Spring, runtime
weaving occurs when the application is running.
Example of AOP in Spring:
1. Aspect Definition:
@Aspect
@Component
public class LoggingAspect {
@Before("execution(* com.example.service.*.*(..))")
public void logBeforeMethod() {
System.out.println("Logging before method execution...");
}
}
2. Service Class:
@Service
public class MyService {
public void performAction() {
System.out.println("Action performed.");
}
}
3. Spring Configuration:
@Configuration
@EnableAspectJAutoProxy
@ComponentScan("com.example")
public class AppConfig {
}
Conclusion:
AOP in Spring helps manage cross-cutting concerns, keeping the code clean, modular, and
maintainable. It provides a declarative way to enhance application behavior without
modifying business logic directly.
(c) Discuss Hibernate architecture in detail.
Ans:- Hibernate Architecture (7 Marks)
Hibernate is a Java ORM (Object-Relational Mapping) framework that provides a powerful
solution for mapping Java objects to relational database tables. It helps in simplifying the
persistence layer by abstracting away database interaction complexities, thus improving
application performance and maintainability.
Core Components of Hibernate Architecture:
1. Configuration Object (Configuration):
o The Configuration object is responsible for setting up Hibernate's
environment and initializing various parameters such as the database
connection, Hibernate properties (like dialect, pool size, etc.), and entity
mappings.
o It reads the hibernate.cfg.xml configuration file (or Java-based configuration)
and prepares Hibernate for the session factory creation.
o It contains all the configuration settings, including database credentials,
dialect, and mapping files.
o It can also programmatically load mappings for specific classes or packages.
2. Session Factory (SessionFactory):
o The SessionFactory is a thread-safe, immutable object used to create Session
objects, which are responsible for interacting with the database.
o It is created by the Configuration object and is used throughout the
application for all database interactions.
o SessionFactory manages the mappings, configurations, and cache
mechanisms (first-level cache).
o It is typically created once per application and used throughout the
application lifecycle, ensuring high performance and efficient memory usage.
3. Session (Session):
o The Session object is a single-threaded, lightweight object used to interact
with the database and manage CRUD operations (Create, Read, Update,
Delete).
o A session is created from the SessionFactory and is used for all database
operations in a specific transaction or context.
o A session represents a unit of work: it holds a set of entities and their
associated database transactions.
o Methods like save(), update(), delete(), and createQuery() are invoked on the
Session object to interact with the database.
4. Transaction (Transaction):
o The Transaction interface is responsible for managing transactions in
Hibernate. It ensures data consistency and integrity by grouping multiple
database operations into a single atomic unit of work.
o A transaction can be started, committed, or rolled back using the Session
object.
o Methods like beginTransaction(), commit(), and rollback() are used to manage
transactions.
o The transaction ensures that operations like insertions, updates, and
deletions are completed successfully or rolled back in case of errors.
5. Persistent Objects (POJOs):
o Persistent objects (also known as POJOs) are regular Java objects that are
mapped to database tables in Hibernate.
o These objects are typically annotated with JPA annotations (such as @Entity,
@Table, @Id, etc.) or mapped through XML files.
o Hibernate automatically converts these objects to rows in the database and
vice versa.
o The mapping defines how an object’s fields map to a table’s columns in the
relational database.
6. Hibernate Query Language (HQL):
o HQL (Hibernate Query Language) is an object-oriented query language used
to query the database using Java objects instead of SQL queries.
o HQL queries operate on persistent objects (entities), and you can query the
attributes of the Java objects rather than database columns.
o It supports both simple queries and complex queries (joins, aggregations,
etc.), providing a rich and flexible querying mechanism.
7. Caching Mechanism: Hibernate supports two levels of caching:
o First-Level Cache: This cache is associated with the Session and is enabled by
default. It caches objects that are loaded or saved during the session’s
lifecycle. The first-level cache reduces the need to load the same object
multiple times within the same session.
o Second-Level Cache: This cache is associated with the SessionFactory and can
be used to cache entities, collections, and queries across sessions. It is an
optional cache, providing better performance by reducing database access. It
is often used with external caching solutions like Ehcache or Infinispan.
8. Interceptor:
o The Interceptor interface allows users to hook into Hibernate's lifecycle
events (like before save, after update, etc.) and define custom behavior.
o Interceptors can be used for logging, auditing, or modifying the data during
various lifecycle stages (e.g., before saving an entity or after loading data).
Hibernate Architecture Diagram:
+---------------------------------------+
| Application Code |
+---------------------------------------+
|
V
+---------------------------------------+
| Configuration Object |
| (hibernate.cfg.xml or Java config) |
+---------------------------------------+
|
V
+---------------------------------------+
| SessionFactory |
| (Creates Sessions for DB operations)|
+---------------------------------------+
|
V
+---------------------------------------+
| Session (Unit of Work) |
| (Perform CRUD operations, querying) |
+---------------------------------------+
|
V
+---------------------------------------+
| Transaction |
| (Control Commit/Rollback) |
+---------------------------------------+
|
V
+---------------------------------------+
| Persistent Objects (POJOs) |
| (Mapped to DB Tables) |
+---------------------------------------+
|
V
+---------------------------------------+
| Hibernate Query Language (HQL) |
| (For querying data) |
+---------------------------------------+
|
V
+---------------------------------------+
| Caching Mechanism |
| (First-Level and Second-Level) |
+---------------------------------------+
Hibernate Workflow:
1. Configuration: A Configuration object is created to read the hibernate.cfg.xml file,
which contains the necessary database connection properties and entity mappings.
2. SessionFactory: Using the configuration, a SessionFactory is created. This object will
be responsible for creating Session instances.
3. Session: A Session object is obtained from the SessionFactory. This session is used to
perform database operations like saving, updating, deleting, and querying persistent
objects.
4. Transaction: Transactions are started with beginTransaction(). When the operations
are completed, the transaction is either committed or rolled back using commit() or
rollback() to ensure data consistency.
5. Persistent Objects (POJOs): The Java objects (POJOs) are persisted in the database
using the session's save(), update(), or delete() methods. These POJOs are mapped to
database tables using annotations or XML configuration.
6. HQL: To query the database, Hibernate uses HQL, which queries the persistent
objects instead of tables, making it more flexible and object-oriented.
7. Caching: Hibernate uses first-level cache to store data within a session and second-
level cache to store data across multiple sessions, improving application
performance by reducing database queries.
Conclusion:
Hibernate architecture simplifies data interaction in Java applications by mapping Java
objects to relational database tables, abstracting the complexities of SQL queries, and
providing powerful features like HQL, caching, and transaction management. The design of
Hibernate ensures that database interactions are more efficient, clean, and maintainable,
making it one of the most widely used ORM frameworks in Java.
OR Q.5 (a) What is Hibernate? What are the features of it?
Ans:- What is Hibernate?
Hibernate is an Object-Relational Mapping (ORM) framework for Java, which simplifies
database interactions by mapping Java objects (POJOs) to relational database tables. It
abstracts low-level JDBC code and provides a high-level API for performing CRUD (Create,
Read, Update, Delete) operations on a database using Java objects.
Features of Hibernate:
1. Object-Relational Mapping (ORM):
o Hibernate automatically maps Java objects to relational database tables,
eliminating the need for writing SQL to interact with the database.
2. HQL (Hibernate Query Language):
o Hibernate provides a powerful, object-oriented query language called HQL,
which allows querying using Java objects and their properties instead of SQL.
3. Caching:
o Hibernate supports first-level cache (session cache) and second-level cache
(across sessions), improving performance by reducing redundant database
queries.
4. Lazy Loading:
o Hibernate supports lazy loading, meaning related entities are loaded only
when accessed, optimizing resource usage and performance.
5. Transaction Management:
o Hibernate integrates with Java's transaction management (JTA and JDBC),
allowing efficient handling of database transactions.
These features help developers interact with databases more easily and efficiently,
abstracting much of the complexity of manual JDBC code.
(b) Explain OR mapping using hibernate mapping file.
Ans:- OR Mapping using Hibernate Mapping File
Object-Relational (OR) Mapping in Hibernate refers to the process of mapping Java objects
to database tables. Hibernate uses mapping files (XML files) or annotations to define how
Java objects and their properties relate to database tables and columns. The mapping file
provides instructions on how Hibernate should persist and retrieve Java objects from the
database.
Steps for OR Mapping Using Hibernate Mapping File:
1. Create a Java Class (POJO):
o Define a Java class that represents the entity, with fields corresponding to the
columns in the database table.
o Example:
o public class Student {
o private int id;
o private String name;
o private int age;
o
o // Getters and Setters
o }
2. Create a Hibernate Mapping File (.hbm.xml):
o The Hibernate mapping file defines how the class fields are mapped to
database columns.
o The mapping file is typically placed in the src directory and is referenced in
the Hibernate configuration file (hibernate.cfg.xml).
Example of a Hibernate mapping file (Student.hbm.xml):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Student" table="students">
<id name="id" column="student_id">
<generator class="increment"/>
</id>
<property name="name" column="name" />
<property name="age" column="age" />
</class>
</hibernate-mapping>
o <class>: Maps the Java class to the database table (students table).
o <id>: Maps the primary key (here, id field) to the database's primary key
column (student_id). The generator specifies how the ID is generated (e.g.,
increment).
o <property>: Maps the class fields (name, age) to the corresponding database
columns (name, age).
3. Configure Hibernate:
o The Hibernate configuration file (hibernate.cfg.xml) must be set up to
reference the mapping files and define database connection details.
Example hibernate.cfg.xml:
<hibernate-configuration>
<session-factory>
<!-- JDBC Database connection settings -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</
property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/testdb</
property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<!-- Echo all executed SQL to stdout -->
<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- Mention annotated class -->
<mapping resource="Student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
4. Use Hibernate to Persist Data:
o After setting up the mapping file and configuration, Hibernate can be used to
save, retrieve, update, and delete Java objects to/from the database.
Example of using Hibernate in a Java program:
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Student student = new Student();
student.setName("John Doe");
student.setAge(22);
session.save(student);
transaction.commit();
session.close();
Summary:
OR Mapping in Hibernate maps Java classes to database tables through the use of
mapping files.
The mapping file (.hbm.xml) specifies how each Java field maps to a column in the
database.
The Hibernate configuration file (hibernate.cfg.xml) links the mapping files and
provides database connection settings.
(c) Discuss Spring framework architecture in detail.
Ans:- Spring Framework Architecture (7 Marks)
The Spring Framework is a comprehensive, lightweight, and modular framework used to
develop Java applications. It provides support for developing enterprise-grade applications
by promoting good design practices such as dependency injection (DI), aspect-oriented
programming (AOP), and transaction management. Spring simplifies Java development by
providing a consistent, easy-to-use infrastructure for building and deploying applications.
Core Components of the Spring Framework Architecture:
1. Core Container: The core container is the backbone of the Spring framework. It is
responsible for providing the fundamental features of the Spring framework such as
dependency injection and bean management.
o BeanFactory:
This is the simplest container in Spring. It is responsible for loading
beans, wiring dependencies, and providing them when needed. It is
used primarily for low-memory environments or when performance is
a key consideration.
o ApplicationContext:
This is a more advanced version of the BeanFactory. It provides
additional features such as event propagation, message resources,
and AOP (Aspect-Oriented Programming) integration.
It also supports internationalization (i18n) and is the most widely used
container in Spring-based applications.
The ApplicationContext and BeanFactory are responsible for managing the lifecycle of
beans and performing dependency injection (DI), where beans are automatically wired into
each other by the container.
2. Spring Beans:
o In Spring, objects that are managed by the Spring container are referred to as
beans.
o A bean is an object that is instantiated, assembled, and managed by the
Spring container. Beans are configured using XML configuration files,
annotations, or Java-based configuration classes.
o Dependency Injection (DI) is the mechanism through which Spring resolves
bean dependencies and injects them at runtime.
3. AOP (Aspect-Oriented Programming):
o AOP is a programming paradigm that allows separating cross-cutting
concerns, such as logging, security, and transaction management, from the
business logic of the application.
o Spring AOP allows for applying cross-cutting concerns to various parts of an
application by defining aspects.
o The main components of AOP in Spring are:
Aspect: A modularization of cross-cutting concerns.
Joinpoint: A point in the execution of the program (method
invocation) where an aspect can be applied.
Advice: The action taken by an aspect at a particular joinpoint (before,
after, or around a method).
Pointcut: An expression that matches joinpoints to which advice
should be applied.
4. Data Access Layer:
o Spring provides a simplified, consistent approach to working with databases
through the JDBC abstraction layer. It also supports object-relational
mapping (ORM) frameworks such as Hibernate, JPA (Java Persistence API),
and MyBatis.
o Spring's JDBC Template simplifies the interaction with the database by
eliminating boilerplate code such as connection management and exception
handling.
o Transaction management is also part of this layer, enabling declarative
transaction management and ensuring consistency during database
operations.
5. Transaction Management:
o Spring provides a comprehensive, consistent mechanism for transaction
management across different types of transactional resources (such as
databases, message queues, etc.).
o Spring supports declarative transaction management via annotations like
@Transactional, which simplifies transaction management by eliminating the
need for explicit code in application logic.
6. Spring MVC (Model-View-Controller):
o Spring MVC is a powerful framework for building web applications. It follows
the Model-View-Controller design pattern, which separates the application
logic into three components:
Model: Represents the application data and business logic.
View: Represents the presentation layer (typically JSP, Thymeleaf, or
other templating engines).
Controller: Manages user requests and updates the model, selecting
the appropriate view.
o DispatcherServlet is the central component in Spring MVC that acts as the
controller and dispatches requests to appropriate handlers (controllers).
o Handler Mappings, View Resolvers, and Message Converters are key
components for request handling and view rendering in Spring MVC.
7. Spring Security:
o Spring Security is a powerful and customizable authentication and
authorization framework. It provides robust protection for applications by
ensuring secure access to resources.
o It supports features like authentication, authorization, CSRF (Cross-Site
Request Forgery) protection, method security, and more.
8. Spring Integration and Messaging:
o Spring Integration provides an easy-to-use framework for building enterprise
integration solutions. It offers adapters for integrating with different
protocols (such as HTTP, JMS, FTP, etc.), and supports message-driven
architecture using Spring Messaging.
9. Spring Boot:
o Spring Boot is a special project within the Spring ecosystem that aims to
simplify the setup and configuration of Spring applications. It provides auto-
configuration, embedded servers, and simplifies dependency management.
o Spring Boot allows developers to quickly build production-ready applications
with minimal setup and configuration. It eliminates the need for XML
configurations and reduces the complexity of the Spring development
process.
Spring Framework Architecture Diagram:
+--------------------------------------------------+
| Client Request |
+--------------------------------------------------+
|
v
+--------------------------------------------------+
| DispatcherServlet (Controller) |
+--------------------------------------------------+
|
+--------------------------------------------+
| |
v v
+-------------+ +--------------+
| Handler | | View |
| Mappings | | Resolvers |
+-------------+ +--------------+
|
v
+--------------------------------------------------+
| Service Layer (Business Logic) |
+--------------------------------------------------+
|
v
+--------------------------------------------------+
| Data Access Layer (JDBC, ORM, JPA, etc.) |
+--------------------------------------------------+
|
v
+--------------------------------------------------+
| Transaction Management (Spring TX) |
+--------------------------------------------------+
|
v
+--------------------------------------------------+
| Core Container (BeanFactory, AOP) |
+--------------------------------------------------+
Summary:
Core Container: Manages beans and DI.
AOP: Separates cross-cutting concerns.
Data Access: Simplifies JDBC, ORM, and transaction management.
Spring MVC: A framework for building web applications.
Spring Boot: Simplifies Spring app setup with auto-configuration and embedded
servers.
Spring Security: Ensures authentication and authorization.
The Spring Framework's modular architecture enables developers to choose and use only
the components they need, promoting loose coupling and high cohesion in enterprise
application development.