0% found this document useful (0 votes)
2 views29 pages

Adv Java Notes

Uploaded by

octophoniex
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views29 pages

Adv Java Notes

Uploaded by

octophoniex
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Here is the comprehensive, detailed question bank with structured, exam-oriented answers for

your end-semester examination. The answers are broken down into clean bullet points, clear
definitions, and straightforward code snippets to make them easy to memorize while
maintaining the depth required to score full marks.

Module 1: Introduction to Java EE


1. Explain the architecture of Java EE.

Java EE (Enterprise Edition) follows a 4-tier distributed architecture designed to host


large-scale, scalable, and secure enterprise applications.
●​ Client Tier: Runs on the client machine (e.g., Web browsers, Mobile apps, or standalone
Java GUI applications) and interacts directly with the user.
●​ Web Tier: Runs on the Web Container (inside the Application Server). It consists of
Servlets and JSPs that receive HTTP requests from clients, process business logic, and
generate dynamic HTML responses.
●​ Business Tier (EJB Tier): Runs on the EJB Container. It handles the core business logic,
transaction management, and enterprise security using Enterprise JavaBeans (EJBs).
Note: In modern lightweight architectures, Spring or plain Java classes are often used
here.
●​ Enterprise Information System (EIS) Tier: The data storage layer located on a separate
database server. It includes relational databases (MySQL, Oracle), mainframes, or legacy
systems accessed via JDBC.
2. Differentiate between Java SE and Java EE with suitable examples.

Feature Java SE (Standard Edition) Java EE (Enterprise


Edition)

Core Focus Used for developing Used for developing


desktop, standalone, and large-scale, distributed,
general-purpose secure, and multi-tiered
command-line applications. enterprise web
applications.

Components Core APIs like [Link], Enterprise APIs like Servlets,


[Link], [Link], JavaFX, and JSP, JDBC, JSTL,
Swing. Hibernate/JPA, and EJBs.

Environment Runs directly on the Java Requires an Application


Virtual Machine (JVM) of Server (e.g., GlassFish,
any operating system. WildFly) or a Web
Container (e.g., Apache
Tomcat) to run.

Example Application A local calculator app, a text An online banking system,


editor (Notepad clone), or a an e-commerce platform
standalone media player. (like Amazon), or an
institutional student portal.

3. Describe the role of JDBC in web applications.

JDBC (Java Database Connectivity) serves as the bridge between the Java web application
and the relational database management system (RDBMS).
●​ Data Persistence: Web applications are inherently stateless. JDBC allows the application
to store user data permanently (e.g., saving a user's registration details).
●​ Abstraction: It provides a standard set of interfaces (like Connection, Statement,
ResultSet), allowing developers to write database-independent code. You can switch
from MySQL to Oracle by just changing the driver driver configuration without rewriting
your core SQL queries.
●​ Dynamic Data Rendering: When a user requests data (e.g., viewing an invoice), the
Servlet uses JDBC to fetch the data from the database and pass it to a JSP page to
display it to the user.
4. Explain how JSP and Servlets work together in a web application.

Servlets and JSPs complement each other by separating the Logic from the Presentation (the
foundation of the MVC design pattern).
●​ The Servlet (The Controller): Acts as the entry point for the request. It intercepts the
HTTP request from the browser, validates the input data, communicates with the
database via JDBC to fetch or update records, and stores the resulting data inside scope
objects (like request or session attributes).
●​ The JSP (The View): The Servlet forwards the request to a JSP page. The JSP retrieves
the data stored by the servlet and formats it cleanly inside HTML, CSS, and Bootstrap
tags to present a dynamic interface back to the client.
5. Draw and explain the request–response cycle of a Java EE web
application.

1.​ Request Initiation: The user types a URL or clicks a button on a web browser, sending an
HTTP request across the network.
2.​ Interception: The request hits the Web Server/Container (e.g., Tomcat). The container
maps the URL and directs the request to the designated Servlet.
3.​ Processing: The Servlet extracts form parameters, executes business logic, and queries
the database via JDBC.
4.​ Forwarding: The Servlet attaches the database results to the request object and
forwards it to a JSP page.
5.​ Rendering: The JSP extracts the data, generates a pure HTML page dynamically, and
sends it back to the web container.
6.​ Response Delivery: The Web Container packages the HTML into an HTTP response and
sends it back to the client’s browser for rendering.
6. What are the advantages of Java EE over standalone Java
applications?

●​ Distributed Architecture: Components can run on different machines across a network,


optimizing processing loads.
●​ Built-in Component Containers: Developers don't need to write low-level code for
multithreading, security, or socket connections; the Web Container manages these
automatically.
●​ Scalability & High Availability: Java EE applications can easily scale up (handling more
requests on a single server) or scale out (clustering across multiple servers).
●​ Declarative Security: Security roles and access permissions can be defined directly in
configuration files ([Link]) without touching the core source code.
Short Questions / Viva (Module 1)
●​ Define Java EE: An extension of Java SE that provides a platform, runtime environment,
and a suite of APIs for building large-scale, multi-tiered, reliable, and secure enterprise
web applications.
●​ What is a web container? A component of an application server (like Apache Tomcat)
that manages the lifecycle of Servlets, JSPs, and Filters, handling network requests and
executing web components.
●​ What is the purpose of Servlets? To intercept HTTP requests, process backend
business logic, communicate with databases, and act as controllers in web applications.
●​ What is the purpose of JSP? To simplify the creation of dynamic, data-driven web
pages by allowing developers to write Java code directly inside HTML markup.
●​ What is JDBC used for? To establish database connections, execute SQL statements
(CRUD operations) from a Java application, and process the results returned from
relational databases.

Module 2: JDBC (Java Database


Connectivity)
1. Explain the JDBC architecture and its components.

JDBC features a two-layer architecture: the JDBC API layer (Application-to-JDBC) and the
JDBC Driver layer (JDBC-to-Database).
●​ DriverManager: This class manages the list of database drivers. It matches connection
requests from the Java application with the proper database driver using a
communication URL.
●​ Driver: The interface that handles communications with the specific database server.
●​ Connection: This interface represents a physical session with a specific database. All
SQL commands are executed within the context of a connection.
●​ Statement: Used to submit simple, static SQL queries to the database.
●​ PreparedStatement: An advanced interface used to execute pre-compiled SQL queries
with dynamic input parameters.
●​ ResultSet: A table of data representing a database result set generated by executing a
SQL SELECT statement.
2. Discuss different types of JDBC drivers.

There are 4 types of JDBC drivers:


1.​ Type-1: JDBC-ODBC Bridge Driver
○​ Mechanism: Converts JDBC calls into ODBC function calls. It relies on the native ODBC
driver installed on the client machine.
○​ Pros/Cons: Easy to use but offers slow performance; it is now completely obsolete
(removed from Java 8 onwards).
2.​ Type-2: Native-API Driver (Partly Java, Partly Native)
○​ Mechanism: Converts JDBC calls into native client-side database API calls (like Oracle
OCI libraries).
○​ Pros/Cons: Faster than Type-1, but requires database-specific native binary libraries
installed on every client machine, reducing portability.
3.​ Type-3: Network Protocol Driver (Fully Java)
○​ Mechanism: Sends JDBC calls through an intermediate application server (middleware),
which translates the requests into the database-specific protocol.
○​ Pros/Cons: Highly flexible and client-independent, but requires separate middleware
configuration, adding network overhead.
4.​ Type-4: Thin Driver (Fully Java) — Most Widely Used
○​ Mechanism: Converts JDBC calls directly into the vendor-specific database network
protocol.
○​ Pros/Cons: Highest performance, requires no client-side installation, and is written
entirely in Java, making it highly portable.
3. Write steps to establish a JDBC connection.

To connect to a database and execute a query, follow these 5 distinct steps:


1.​ Load the Driver Class: Registers the database driver implementation class into memory.​
Java​
[Link]("[Link]");​

2.​ Establish Connection: Use [Link]() by passing the database


URL, username, and password.​
Java​
Connection con = [Link]("jdbc:mysql://localhost:3006/db_name",
"root", "password");​

3.​ Create a Statement/PreparedStatement Object: Used to hold and send SQL queries.​
Java​
PreparedStatement ps = [Link]("SELECT * FROM students WHERE id = ?");​

4.​ Execute the Query: Run the SQL command. Use executeQuery() for SELECT and
executeUpdate() for INSERT/UPDATE/DELETE.​
Java​
[Link](1, 101);​
ResultSet rs = [Link]();​

5.​ Close Connections: Release database resources to prevent memory leaks.​


Java​
[Link](); [Link](); [Link]();​

4. Compare Statement and PreparedStatement.

Feature Statement PreparedStatement

Compilation Compiles the SQL query Compiles the SQL query


every time it runs. only once during creation,
then saves it for reuse.

Performance Slower when executing the Much faster for repetitive


same query repeatedly with execution because the
different values. database omits parsing and
compilation steps.

Parameters Cannot accept dynamic Accepts dynamic input


runtime input parameters parameters via
directly; requires clumsy placeholders (?) using
string concatenation. setter methods.

Security Vulnerable to SQL Injection Secure against SQL


attacks. Injection attacks because it
escapes input parameters
automatically.
5. Explain ResultSet and ResultSetMetaData.

●​ ResultSet: Represents the tabular rows returned by an executed SQL query. It maintains
a cursor pointing to the current row of data. You navigate forward using [Link](), and
read columns using getter methods like [Link]("id") or [Link]("name").
●​ ResultSetMetaData: An object used to get descriptive information about the
properties of the ResultSet (i.e., data about data). It helps you discover table structures
dynamically at runtime.
○​ Common methods: getColumnCount() (returns total columns), getColumnName(int i)
(returns name of $i^{th}$ column), and getColumnTypeName(int i) (returns data type).
6. Describe transaction management in JDBC using commit, rollback,
and savepoint.

By default, JDBC connections have Auto-Commit mode set to true, meaning every single
SQL statement is saved automatically upon execution. For multi-step transactions, you must
manage this manually:
●​ Disable Auto-Commit: [Link](false);
●​ Commit: Groups your SQL operations into a single logical unit. If all updates succeed,
[Link]() saves all changes permanently to the database.
●​ Rollback: If any SQL operation fails inside a try-catch block, [Link]() undoes all
uncommitted changes made during that transaction block, reverting the database to its
initial state.
●​ Savepoint: Provides additional granularity by setting checkpoints within a transaction.
You can roll back to a specific checkpoint using [Link](savepointObject) without
canceling the entire transaction.
7. Explain batch processing in JDBC and its advantages.

Batch processing allows you to group multiple, related SQL operations together into a batch
and submit them to the database database engine in a single network call.
●​ How it works: You add queries using [Link]("SQL String") or
[Link](), and execute them using [Link]().
●​ Advantages:
1.​ Reduces Network Overhead: Instead of sending 1,000 queries across the network one
by one, you bundle them into a single transmission.
2.​ Improves Database Performance: The database processes the grouped operations
sequentially in memory, reducing disk write overhead and improving throughput.
Programming-Oriented Questions (Module 2)
1 & 2 & 3. Program to Connect to MySQL, Insert, Update, and Delete
using PreparedStatement
Java
import [Link].*;​

public class JDBCDemo {​
private static final String URL = "jdbc:mysql://localhost:3306/college_db";​
private static final String USER = "root";​
private static final String PWD = "password";​

public static void main(String[] args) {​
Connection con = null;​
PreparedStatement psInsert = null;​
PreparedStatement psUpdate = null;​
PreparedStatement psDelete = null;​

try {​
// Step 1: Load driver & get connection​
[Link]("[Link]");​
con = [Link](URL, USER, PWD);​
[Link]("Database Connected successfully!");​

// --- 1. INSERT OPERATION ---​
String insertSql = "INSERT INTO students (id, name, dept) VALUES (?, ?, ?)";​
psInsert = [Link](insertSql);​
[Link](1, 105);​
[Link](2, "Nishan Das");​
[Link](3, "BCA");​
int rowsInserted = [Link]();​
[Link](rowsInserted + " row inserted.");​

// --- 2. UPDATE OPERATION ---​
String updateSql = "UPDATE students SET dept = ? WHERE id = ?";​
psUpdate = [Link](updateSql);​
[Link](1, "MCA");​
[Link](2, 105);​
int rowsUpdated = [Link]();​
[Link](rowsUpdated + " row updated.");​

// --- 3. DELETE OPERATION ---​
String deleteSql = "DELETE FROM students WHERE id = ?";​
psDelete = [Link](deleteSql);​
[Link](1, 105);​
// int rowsDeleted = [Link](); // Uncomment to run delete​

} catch (Exception e) {​
[Link]();​
} finally {​
// Close resources cleanly​
try {​
if (psInsert != null) [Link]();​
if (psUpdate != null) [Link]();​
if (psDelete != null) [Link]();​
if (con != null) [Link]();​
} catch (SQLException se) {​
[Link]();​
}​
}​
}​
}​

4. Program demonstrating Transaction Management (Commit &


Rollback)

Java
import [Link].*;​

public class JDBCTransactionDemo {​
public static void main(String[] args) {​
Connection con = null;​
PreparedStatement psSub = null;​
PreparedStatement psAdd = null;​

try {​
[Link]("[Link]");​
con = [Link]("jdbc:mysql://localhost:3306/bank_db", "root",
"password");​

// Turn off auto-commit​
[Link](false);​

// Step 1: Deduct money from Account A​
psSub = [Link]("UPDATE accounts SET balance = balance - ? WHERE
acc_no = ?");​
[Link](1, 5000.00);​
[Link](2, 101);​
[Link]();​

// Step 2: Add money to Account B​
psAdd = [Link]("UPDATE accounts SET balance = balance + ? WHERE
acc_no = ?");​
[Link](1, 5000.00);​
[Link](2, 102);​
[Link]();​

// If both operations succeed, commit changes permanently​
[Link]();​
[Link]("Transaction Completed and Committed Successfully!");​

} catch (Exception e) {​
[Link]("Transaction failed! Rolling back changes...");​
try {​
if (con != null) [Link](); // Undo everything if an error occurs​
} catch (SQLException se) {​
[Link]();​
}​
[Link]();​
} finally {​
try {​
if (psSub != null) [Link]();​
if (psAdd != null) [Link]();​
if (con != null) [Link]();​
} catch (SQLException se) { [Link](); }​
}​
}​
}​
5. Program using Batch Processing

Java
import [Link].*;​

public class JDBCBatchDemo {​
public static void main(String[] args) {​
Connection con = null;​
PreparedStatement ps = null;​
try {​
[Link]("[Link]");​
con = [Link]("jdbc:mysql://localhost:3306/college_db", "root",
"password");​

String sql = "INSERT INTO students (id, name, dept) VALUES (?, ?, ?)";​
ps = [Link](sql);​

// Add Record 1 to Batch​
[Link](1, 201); [Link](2, "Amit"); [Link](3, "BCA");​
[Link]();​

// Add Record 2 to Batch​
[Link](1, 202); [Link](2, "Rahul"); [Link](3, "BTech");​
[Link]();​

// Execute the combined batch​
int[] results = [Link]();​
[Link]("Batch executed. Total rows inserted: " + [Link]);​

} catch (Exception e) {​
[Link]();​
} finally {​
try { if (ps != null) [Link](); if (con != null) [Link](); } catch (Exception e) {}​
}​
}​
}​
Module 3: Java Server Pages (JSP)
1. Explain the JSP life cycle with a diagram.

A JSP page is transparently converted into a Servlet by the Web Container. Its lifecycle steps
include:
1.​ Translation: The Web Container reads the .jsp file and parses its contents to generate
corresponding Java Servlet source code (a .java file).
2.​ Compilation: The container compiles this .java file into an executable Java bytecode
class (.class file).
3.​ Initialization (jspInit()): The container loads the class into memory and invokes the
jspInit() method to initialize resources like database connections. This runs only once.
4.​ Execution (_jspService()): For every incoming request, the container spawns a thread
and executes _jspService(). This method handles the incoming HttpServletRequest and
generates the HttpServletResponse.
5.​ Destruction (jspDestroy()): When the application is stopped or undeployed, the
container calls jspDestroy() to release any active resources cleanly.
2. Describe JSP syntax and directives.

JSP elements fall into three primary categories:


●​ Directives (<%@ ... %>): Provide global instructions to the container regarding how to
process the JSP page during compilation.
●​ Scripting Elements: Allow developers to insert plain Java code directly inside the page
(e.g., <% ... %>, <%= ... %>, <%! ... %>).
●​ Action Elements (<jsp:... />): XML-like tags that control container behavior dynamically
at runtime (e.g., forwarding requests, using beans).
3. Differentiate between scriptlet, expression, and declaration tags.

Feature Scriptlet Tag (<% Expression Tag Declaration Tag


... %>) (<%= ... %>) (%! ... %>)

Purpose Used to write Used to print values Used to declare


blocks of directly to the global variables or
executable Java output stream methods that
code (loops, without using persist across
conditionals, logic). [Link](). multiple requests.

Semicolon Must end each Do not use a Must end with a


statement with a semicolon at the semicolon (;).
semicolon (;). end of the
expression.

Generated Code Placed inside the Placed directly Placed outside the
Location local _jspService() inside an [Link]() _jspService()
method block. call within method block as
_jspService(). class-level
members.

Example <% int count = 10; <%= count %> <%! public int
%> cube(int n) { return
n*n*n; } %>

4. Explain JSP implicit objects with examples.

JSP provides 9 pre-defined implicit objects that are automatically available inside the
_jspService() method without explicit declaration:
1.​ request: Represents the HttpServletRequest object. Used to read form parameters:
[Link]("username").
2.​ response: Represents the HttpServletResponse object. Used to redirect users:
[Link]("[Link]").
3.​ out: An instance of JspWriter used to send text directly to the response page:
[Link]("Hello");.
4.​ session: Represents HttpSession. Used to store user data across pages:
[Link]("user", name).
5.​ application: Represents the global ServletContext common to all users in the
application.
6.​ config: Represents ServletConfig for page initialization parameters.
7.​ pageContext: Provides access to page namespaces and allows components to share
data across different scopes.
8.​ page: Acts as a reference to the current translated servlet class instance (similar to this in
Java).
9.​ exception: Represents an unhandled Java Throwable object, available only on pages
designated as error pages using <%@ page isErrorPage="true" %>.
5. What are JSP action elements? Explain <jsp:useBean> and
<jsp:include>.

Action elements are XML tags that perform built-in operations at runtime.
●​ <jsp:useBean>: Locates or instantiates a reusable JavaBean class object.
○​ Syntax: <jsp:useBean id="student" class="[Link]" scope="request"/>
●​ <jsp:setProperty>: Sets properties inside the target bean: <jsp:setProperty
name="student" property="name" value="Nishan"/>
●​ <jsp:getProperty>: Retrieves a property value from a bean and inserts it into the text
response: <jsp:getProperty name="student" property="name"/>
●​ <jsp:include>: Dynamically includes the response of another resource (HTML, JSP, or
Servlet) while the page is executing.
○​ Syntax: <jsp:include page="[Link]" />
6. Explain JSP Expression Language (EL).

JSP Expression Language (EL) simplifies accessing application data stored in JavaBeans or
scope attributes (page, request, session, application), eliminating the need to write traditional
Java scripting tags.
●​ Syntax: ${expression}
●​ Example: Instead of typing <%= (([Link])[Link]("user")).getName()
%>, you can write: ${[Link]}.
●​ It handles null pointers safely, returning an empty string instead of throwing a
NullPointerException.
7. Discuss JSTL core tags with examples.

The JavaServer Pages Standard Tag Library (JSTL) replaces scriptlet logic with standardized
XML tags. The Core tag library handles iteration, conditional rendering, and URL management:
●​ <c:if>: Standard conditional test statement.​
Java​
<c:if test="${[Link] == 'admin'}"> <p>Welcome Admin!</p> </c:if>​

●​ <c:choose>, <c:when>, <c:otherwise>: Functions exactly like a Java switch-case block.​


Java​
<c:choose>​
<c:when test="${marks >= 60}">First Class</c:when>​
<c:otherwise>Passed</c:otherwise>​
</c:choose>​

●​ <c:forEach>: Iterates over loops or collection items.​


Java​
<c:forEach var="item" items="${itemList}"> <li>${item}</li> </c:forEach>​

8. What is a custom tag library? Explain its benefits.

A custom tag library allows developers to define their own application-specific XML tags to
encapsulate complex, repetitive Java code. It requires a Java Handler Class that implements
the SimpleTagSupport interface and a Tag Library Descriptor (TLD) configuration XML file.
●​ Benefits:
1.​ Code Reusability: Complex operations can be packaged once into a single tag and
reused across multiple pages.
2.​ Cleaner Codebases: Removes distracting Java source code from presentation markup,
allowing web designers to manage layouts without knowing backend Java programming.
Programming-Oriented Questions (Module 3)
1. JSP Page demonstrating Scriptlet, Expression, and Declaration Tags

Java
<%@ page language="java" contentType="text/html; charset=UTF-8" %>​
<html>​
<head><title>Scripting Elements</title></head>​
<body>​
<%-- 1. Declaration Tag --%>​
<%! ​
public int square(int x) {​
return x * x;​
}​
%>​

<%-- 2. Scriptlet Tag --%>​
<%​
int input = 5;​
int result = square(input);​
%>​

<%-- 3. Expression Tag --%>​
<h3>Square of <%= input %> is: <%= result %></h3>​
</body>​
</html>​

2. JSP Page using implicit objects (request and session)


Java
<html>​
<body>​
<%-- Read request parameter sent via form [Link]?user=Nishan --%>​
String username = [Link]("user");​

if(username != null) {​
// Save user name inside session scope​
[Link]("currentUser", username);​
}​

// Retrieve value out from session scope​
String sessionUser = (String) [Link]("currentUser");​
%>​
<h2>Welcome user: <%= sessionUser %></h2>​
</body>​
</html>​

3. JSP Page using JSTL <c:forEach> and <c:if> tags

Java
<%@ taglib prefix="c" uri="[Link] %>​
<%​
// Mock array list initialized using scriptlet for demo​
String[] fruits = {"Apple", "Banana", "Orange", "Mango"};​
[Link]("fruitList", fruits);​
%>​
<html>​
<body>​
<h3>Fruit Inventory Check:</h3>​
<ul>​
<c:forEach var="f" items="${fruitList}">​
<li>​
${f} ​
<c:if test="${f == 'Mango'}"><b> - In Season!</b></c:if>​
</li>​
</c:forEach>​
</ul>​
</body>​
</html>​

4. Create a JSP page that uses JavaBeans

First, the Java Bean class ([Link]):

Java
package [Link];​
import [Link];​

public class Student implements Serializable {​
private String name;​
public Student() {} // Mandatory zero-argument constructor​
public void setName(String name) { [Link] = name; }​
public String getName() { return name; }​
}​

Next, the JSP File ([Link]):

Java
<html>​
<body>​
<jsp:useBean id="stuObj" class="[Link]" scope="request" />​

<jsp:setProperty name="stuObj" property="name" value="Nishan Das" />​

<h2>Student Name: <jsp:getProperty name="stuObj" property="name" /></h2>​
</body>​
</html>​
Module 4: Servlets
1. Explain the Servlet life cycle with a diagram.

The Servlet lifecycle is managed entirely by the Web Container. It consists of 3 main phases:
1.​ Loading and Instantiation: The Web Container loads the Servlet class into memory
when the server starts up or when the first matching client request is received.
2.​ Initialization (init()): The container calls the init(ServletConfig config) method to initialize
setup resources. This runs only once during the servlet's lifespan.
3.​ Request Handling (service()): For every incoming client request, the container invokes
the service() method in a separate thread. This method determines the type of HTTP
request (GET, POST, etc.) and dispatches it to the appropriate handler method (doGet(),
doPost()).
4.​ Destruction (destroy()): When the server is shutting down or resources are being
reclaimed, the container calls destroy() to safely close active connections.
2. Describe how HTTP requests and responses are handled in Servlets.

●​ The Request (HttpServletRequest): When a client submits an HTTP request, the


container packages the request header, query parameters, cookies, and input fields into
an HttpServletRequest object. The Servlet extracts these parameters using methods like
[Link]("fieldName").
●​ The Response (HttpServletResponse): The servlet uses an HttpServletResponse object
to format the outgoing response back to the client. Developers set the response content
type via [Link]("text/html") and obtain an output print writer instance
using [Link]() to output HTML markup text.
3. Explain the purpose of the deployment descriptor ([Link]).

The [Link] file, located inside the WEB-INF/ directory, acts as the Deployment Descriptor
Configuration File for a Java Web Application.
●​ Purpose: It gives structural assembly assembly instructions to the Web Container.
●​ Key Operations:
1.​ Defines Servlets and maps them to specific public URL endpoints.
2.​ Configures global application initialization configuration values (context-param).
3.​ Sets session timeout intervals.
4.​ Defines error pages (e.g., mapping HTTP 404 errors to a custom friendly error page).
4. Differentiate between ServletConfig and ServletContext.

Feature ServletConfig ServletContext

Scope One ServletConfig instance One global ServletContext


exists per distinct Servlet instance exists for the
definition. entire web application
deployment.

Data Visibility Initialization parameters are Initialization parameters are


private and accessible only global and accessible to all
inside that specific servlet. Servlets, JSPs, and filters in
the application.

Configuration Tag Defined inside individual Defined globally inside the


<servlet> configurations via root XML element via
<init-param>. <context-param>.

Usage Example Storing an internal text Storing a shared global


layout style sheet name production database
used only by one servlet. connection URL string.

5. Discuss session management techniques in Servlets.

HTTP is a stateless protocol, meaning servers treat each request as completely independent.
Session management keeps track of user identities across requests using 4 main techniques:
1.​ Cookies: Small text files containing a unique Session ID stored inside the user's browser.
2.​ HTTPSession API (Best Practice): A server-side solution where the container
automatically creates a unique session object for each user and manages the matching
tracking keys.
3.​ URL Rewriting: Appends the unique tracking token directly to every active internal URL
path link (e.g., [Link];jsessionid=9928374).
4.​ Hidden Form Fields: Inserts invisible inputs into HTML forms to pass state data between
pages: <input type="hidden" name="userId" value="123">.
6. Explain cookies and their uses.

A cookie is a small key-value text pair sent by a servlet within an HTTP response and stored
locally by the user's browser.
●​ How it works: The servlet creates a cookie using Cookie c = new Cookie("user", "Nishan");
[Link](c);. On subsequent requests, the browser sends the cookie back,
and the servlet reads it using [Link]().
●​ Common Uses:
1.​ Storing user preferences (e.g., light/dark mode settings).
2.​ Tracking persistent "Remember Me" login status.
3.​ Tracking items in a retail shopping cart.
7 & 8. What is servlet chaining? Explain servlet filters with an example.
●​ Servlet Chaining: An architecture where the output response of one servlet is passed as
the input to another servlet for further processing, creating a sequential execution
pipeline.
●​ Servlet Filters: Java classes that intercept requests and responses before they reach a
target servlet or JSP. They are ideal for cross-cutting concerns like logging,
authentication checks, or data compression.
Filter Implementation Example:

Java
import [Link].*;​
import [Link];​

public class LogFilter implements Filter {​
public void init(FilterConfig fConfig) throws ServletException {}​

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)​
throws IOException, ServletException {​
// Log incoming traffic data​
[Link]("Filter intercepted a request from: " + [Link]());​

// Pass request down the chain to the target servlet​
[Link](request, response);​
}​
public void destroy() {}​
}​

9. Describe file upload and download in Servlets.

●​ File Upload: Handled using the @MultipartConfig annotation on top of the servlet class.
The servlet uses [Link]("fileFieldName") to retrieve data streams from multipart
forms and saves them to a server disk path using [Link]("destination_path").
●​ File Download: The servlet reads the target file from the server's disk into an input
stream, sets the HTTP response headers via
[Link]("application/octet-stream") and
[Link]("Content-Disposition", "attachment; filename=\"[Link]\""), and
writes the file bytes directly to the response output stream.
Programming-Oriented Questions (Module 4)
1. Write a servlet that handles GET and POST requests

Java
import [Link].*;​
import [Link].*;​
import [Link];​
import [Link];​
import [Link];​

@WebServlet("/ProcessServlet")​
public class ProcessServlet extends HttpServlet {​

// Handles hyper-links or direct URL searches​
protected void doGet(HttpServletRequest request, HttpServletResponse response) ​
throws ServletException, IOException {​
[Link]("text/html");​
PrintWriter out = [Link]();​
[Link]("<h2>Handled incoming HTTP GET request successfully!</h2>");​
}​

// Handles form submissions containing payload data​
protected void doPost(HttpServletRequest request, HttpServletResponse response) ​
throws ServletException, IOException {​
[Link]("text/html");​
PrintWriter out = [Link]();​
String user = [Link]("txtName");​
[Link]("<h2>Handled HTTP POST request. Hello: " + user + "</h2>");​
}​
}​

2. Write a servlet demonstrating session management using


HttpSession
Java
@WebServlet("/SessionServlet")​
public class SessionServlet extends HttpServlet {​
protected void doGet(HttpServletRequest request, HttpServletResponse response) ​
throws ServletException, IOException {​
[Link]("text/html");​
PrintWriter out = [Link]();​

// Fetch existing session; create a new one if none exists​
HttpSession session = [Link](true);​

Integer counter = (Integer) [Link]("visitCount");​
if(counter == null) {​
counter = 1;​
} else {​
counter += 1;​
}​
[Link]("visitCount", counter);​

[Link]("<h3>Your Unique Session ID: " + [Link]() + "</h3>");​
[Link]("<h3>Total Session Page Visits: " + counter + "</h3>");​
}​
}​

Module 5: JSP and Servlet Integration


1. Explain how JSP and Servlets are combined in web applications.

In real-world web applications, Servlets and JSPs are combined to build clean architectures.
Servlets act as the backend entry engine that handles incoming forms, performs validations,
calls databases via JDBC, and maps data. JSPs are restricted to rendering views, taking output
data attributes passed from the servlet and displaying them using clean HTML layouts or JSTL
tags.
2. Describe the MVC architecture and its advantages.

Model-View-Controller (MVC) is a architectural pattern that breaks an application into 3 core


layers:
●​ Model: Represents the data and application core business rules (e.g., plain Java objects,
Beans, Hibernate entities).
●​ View: Represents the visual interface presented to the end user (e.g., JSP, HTML pages).
●​ Controller: Acts as the intermediary link interface between Model and View (e.g.,
Servlets). It processes requests, updates models, and selects which view to display.
●​ Advantages:
1.​ Separation of Concerns: UI designers and backend developers can work in parallel
without overwriting each other's code.
2.​ High Maintainability: Modifying backend business rules won't break your frontend
layout pages.
3 & 4. Differentiate between Forward and Redirect.

Feature Request Dispatcher Response sendRedirect()


forward()

Execution Site Performed entirely on the Performed via the


server-side internally. client-side browser.

Network Requests Only 1 request/response Requires 2 distinct


cycle occurs across the independent round-trip
network. requests.

Browser URL Bar The URL remains The URL bar changes to
unchanged, masking the display the new landing
internal file location from page location address.
users.

Data Retention Keeps request scope Clears original request


attributes intact and scopes; data must be saved
accessible on the to the session to persist.
destination page.

Syntax [Link] [Link]("tar


her("[Link]").forward(re [Link]");
quest, response);

Programming-Oriented Questions (Module 5)


1 & 2. Build a simple MVC Login Application using Servlet and JSP

Step 1: Create the Controller Servlet ([Link]):


Java
import [Link].*;​
import [Link].*;​
import [Link];​
import [Link];​

@WebServlet("/LoginController")​
public class LoginServlet extends HttpServlet {​
protected void doPost(HttpServletRequest request, HttpServletResponse response) ​
throws ServletException, IOException {​

String user = [Link]("uid");​
String pass = [Link]("pwd");​

// Model validation logic (simplified for demo)​
if([Link]("admin") && [Link]("1234")) {​
// Success: Pass data via Request Attribute and Forward​
[Link]("msg", "Authorized Entry");​
[Link]("[Link]").forward(request, response);​
} else {​
// Failure: Redirect back to login index page​
[Link]("login_error.html");​
}​
}​
}​

Step 2: Create the Target Success View ([Link]):

Java
<html>​
<head><title>Dashboard View</title></head>​
<body>​
<%-- Read forwarded attribute data safely --%>​
<h2>System Access Status: <%= [Link]("msg") %></h2>​
<h3>Welcome back, Administrator! External operational parameters are green.</h3>​
</body>​
</html>​

Module 6: Hibernate Framework


1. What is Hibernate? Explain its architecture and core components.

Hibernate is an Object-Relational Mapping (ORM) framework for Java. It maps application


domain object models directly to relational database tables, eliminating low-level SQL JDBC
development.
●​ Configuration: Reads settings from [Link] or annotations to build the
application's database runtime engine.
●​ SessionFactory: A heavy, thread-safe factory object used to generate database
sessions. Usually instantiated once per application lifespan.
●​ Session: Represents a single-threaded unit of work with the physical database, providing
core CRUD methods like save(), update(), and delete().
●​ Transaction: A single-threaded object used to manage atomic database operations.
●​ Query / Criteria: Interfaces used to retrieve and filter data from the database using HQL
or programmatic object criteria.
2. Discuss the advantages of ORM over JDBC.

●​ Eliminates Boilerplate Code: Removes the need to write repetitive code for
opening/closing connections, statements, or manual map reading from result sets.
●​ Object-Oriented Queries: Allows developers to interact with databases using Java
objects instead of writing raw SQL strings.
●​ Database Dialect Abstraction: Supports cross-database independence. If you switch
from MySQL to Oracle, you don't need to rewrite your SQL; you just update the Hibernate
Dialect property config.
●​ Built-in Caching: Features structural first-level (session) and second-level caching
mechanisms to reduce redundant database queries and improve performance.
3 & 4. Describe mapping Java Classes to Database Tables using
Annotations.

Hibernate allows you to map plain Java classes (POJOs) to database tables using metadata
annotations:
●​ @Entity: Marks the Java class as a persistent database entity component.
●​ @Table(name="..."): Maps the class to a specific relational database table name.
●​ @Id: Specifies the primary key column field of the entity.
●​ @GeneratedValue: Configures automatic ID generation strategies (e.g.,
auto-incrementing integers).
●​ @Column(name="..."): Maps a Java object property field to a specific database column
name.
5 & 7. Explain SessionFactory, Session, and basic CRUD operations in
Hibernate.

●​ SessionFactory creates short-lived Session instances.


●​ The Session interface provides built-in methods to perform CRUD operations without
writing SQL strings:
○​ Create: [Link](studentObject);
○​ Read / Retrieve: Student s = [Link]([Link], 101);
○​ Update: [Link](studentObject);
○​ Delete: [Link](studentObject);
●​ All data updates must run within an active Transaction block ([Link]()).
6. What is HQL? Compare HQL with SQL.

Hibernate Query Language (HQL) is an object-oriented extension of SQL that queries


database elements using Entity Class names and properties instead of direct database table
names and column headers.
Feature SQL (Structured Query HQL (Hibernate Query
Language) Language)

Target Element Queries tables and column Queries mapped Java


headers directly in the Entity Classes and their
database. properties.

Case Sensitivity Generally case-insensitive Case-sensitive regarding


for table structures. Java class names (Student
vs student).

Portability Queries use Fully portable; Hibernate


database-specific syntax, translates HQL into the
which can break if you correct target SQL
change databases. automatically.

Wildcards Supports SELECT * style Does not support * queries;


wildcard requests. uses object references like
FROM Student s.
Programming-Oriented Questions (Module 6)
1 & 2 & 4. Complete Annotated Entity & Hibernate CRUD Program

Step 1: The Mapped Entity Class ([Link]):

Java
package [Link];​

import [Link].*;​

@Entity​
@Table(name = "student_tbl")​
public class Student {​
@Id​
@GeneratedValue(strategy = [Link])​
@Column(name = "std_id")​
private int id;​

@Column(name = "std_name")​
private String name;​

// Constructors, Getters, and Setters​
public Student() {}​
public Student(String name) { [Link] = name; }​
public int getId() { return id; }​
public String getName() { return name; }​
public void setName(String name) { [Link] = name; }​
}​

Step 2: Executing CRUD Operations Engine Class:


Java
package [Link];​

import [Link];​
import [Link];​
import [Link];​
import [Link];​

public class HibernateCRUDApp {​
public static void main(String[] args) {​
// Instantiate configuration setup engine​
SessionFactory factory = new Configuration()​
.configure("[Link]")​
.addAnnotatedClass([Link])​
.buildSessionFactory();​

// Open a work session unit​
Session session = [Link]();​
Transaction tx = null;​

try {​
tx = [Link]();​

// 1. SAVE/CREATE OPERATION​
Student s1 = new Student("Nishan Das");​
[Link](s1);​
[Link]("Record Saved successfully!");​

// 2. RETRIEVE/READ OPERATION​
Student fetchedStudent = [Link]([Link], [Link]());​
[Link]("Fetched Student Name: " + [Link]());​

// 3. UPDATE OPERATION​
[Link]("Nishan Kumar Das");​
[Link](fetchedStudent);​

// 4. DELETE OPERATION​
// [Link](fetchedStudent); // Uncomment to perform deletion​

[Link](); // Save changes permanently​
} catch (Exception e) {​
if (tx != null) [Link]();​
[Link]();​
} finally {​
[Link]();​
[Link]();​
}​
}​
}​

3. Program demonstrating Data Retrieval using HQL (Hibernate Query


Language)

Java
package [Link];​

import [Link];​
import [Link];​
import [Link];​
import [Link];​

public class HibernateHQLDemo {​
public static void main(String[] args) {​
SessionFactory factory = new Configuration()​
.configure("[Link]")​
.addAnnotatedClass([Link])​
.buildSessionFactory();​

Session session = [Link]();​

try {​
[Link]();​

// Note: 'Student' refers to the Java Class Name, not the database table​
List<Student> students = [Link]("FROM Student s WHERE [Link] LIKE
'Nishan%'", [Link])​
.getResultList();​

for(Student s : students) {​
[Link]("HQL Output Result: ID=" + [Link]() + " Name=" + [Link]());​
}​

[Link]().commit();​
} finally {​
[Link]();​
[Link]();​
}​
}​
}​

You might also like