Adv Java Notes
Adv Java Notes
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.
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?
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.
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]();
● 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]();
}
}
}
}
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.
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; } %>
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>
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>
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>
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; }
}
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 [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.
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() {}
}
● 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>");
}
}
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.
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.
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>
● 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.
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; }
}
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]();
}
}
}