0% found this document useful (0 votes)
14 views43 pages

Advanced Java Servlet Lifecycle Guide

The document provides comprehensive notes on Advanced Java and J2EE, focusing on Servlets and their lifecycle, including definitions, advantages, and detailed working mechanisms. It explains the role of Apache Tomcat as a servlet container, the Servlet API, and how to handle client requests and responses. Additionally, it includes examples of servlet code, configuration, and methods for reading parameters from client requests.

Uploaded by

dinor2286
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)
14 views43 pages

Advanced Java Servlet Lifecycle Guide

The document provides comprehensive notes on Advanced Java and J2EE, focusing on Servlets and their lifecycle, including definitions, advantages, and detailed working mechanisms. It explains the role of Apache Tomcat as a servlet container, the Servlet API, and how to handle client requests and responses. Additionally, it includes examples of servlet code, configuration, and methods for reading parameters from client requests.

Uploaded by

dinor2286
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

Advanced Java and J2EE 23SCS052

SRINIVAS UNNIVERSITY
INSTITUTE OF ENGINEERING AND TECHNOLOGY
MUKKA

Department of Computer Science and Engineering

NOTES

ADVANCED JAVA AND J2EE


Subject code : 23SCS052

COMPILED BY

Ms. Shravya Suvarna


Assistant Professor
CSE Department

2025 – 26

1
Advanced Java and J2EE 23SCS052

Module 4:

Introduction to Servlets and Lifecycle:


Definition:
A Servlet is a server-side Java program that handles client requests and generates
dynamic web content (such as HTML pages).
Servlets are part of the Java EE (Jakarta EE) platform and are managed by a web
container (e.g., Tomcat).
They run inside the server and act as the controller between a web client (browser)
and the backend resources like databases or files.

Purpose / Advantages of Servlets:


• Dynamic Web Content Generation:
Servlets can create responses dynamically based on client input.
• Platform Independent:
Written in Java, so they work on any platform supporting Java.
• Better Performance:
Unlike CGI, Servlets use multi-threading, not multiple processes.
• Secure and Scalable:
Support features like authentication, session tracking, and filters.
• Easy Integration:
Integrate with JDBC for database access and JSP for presentation.
• Reusable and Maintainable:
Modular design allows code reuse and separation of logic from design.

Detailed Working:
• When a web client (browser) sends a request to a servlet:
• The request is sent to the web server (Tomcat).
• The Servlet container loads the servlet class (if not loaded already).
• It calls the servlet’s init() method once to initialize it.
• For each client request, the container invokes the service() method.
• The service() method calls doGet() or doPost() depending on the request
type.
• After serving requests, the container calls the destroy() method before
unloading the servlet.

Syntax:
import [Link].*;
import [Link].*;
import [Link].*;

public class MyServlet extends HttpServlet {

2
Advanced Java and J2EE 23SCS052

public void init() throws ServletException {


// Initialization code
}

public void doGet(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {

[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<h3>Welcome to Java Servlets!</h3>");
}

public void destroy() {


// Cleanup code
}
}

Code Explanation:

Import statements:
Required to use servlet classes ([Link] and [Link]).

Extending HttpServlet:
The class extends HttpServlet to handle HTTP requests.

init() method:
Called once when the servlet is first loaded into memory.

doGet() method:
Handles client’s GET request and sends HTML response.

destroy() method:
Called once before the servlet is unloaded, used to release resources.

Important Methods in Servlet Lifecycle:


Method Description
init() Initializes the servlet; called once when loaded.
service() Called for each request; dispatches to doGet() or doPost().
doGet() Handles GET requests (data retrieval).
doPost() Handles POST requests (data submission).
destroy() Called once before servlet destruction.

3
Advanced Java and J2EE 23SCS052

Example: Servlet Lifecycle Demonstration


import [Link].*;
import [Link].*;
import [Link].*;

public class LifecycleDemo extends HttpServlet {

public void init() throws ServletException {


[Link]("Servlet initialized");
}

public void service(HttpServletRequest req, HttpServletResponse res)


throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<h2>Servlet is handling the request</h2>");
}

public void destroy() {


[Link]("Servlet destroyed");
}
}

Example Explanation:
• When the servlet is first requested, init() runs once.
• For every request, service() runs and sends HTML to the browser.
• When the server stops or reloads the servlet, destroy() runs.

Thus, the servlet lifecycle is:


Loading → init() → service() → destroy()

Conclusion:
Servlets are the foundation of Java web programming.
They efficiently process client requests, generate dynamic content, and manage
state using session tracking.
Their lifecycle is managed automatically by the Servlet Container, providing a
robust, scalable, and platform-independent solution for web applications.

Notes:

• Every servlet must be configured using [Link] or annotations


(@WebServlet).
• Servlet container (like Tomcat) controls servlet lifecycle automatically.
4
Advanced Java and J2EE 23SCS052

• Servlets can communicate with databases using JDBC.


• Servlet = Controller, JSP = View in MVC architecture.
• Common containers: Apache Tomcat, Jetty, GlassFish.

Using Tomcat for Servlet Development and a Simple Servlet Example:


Definition:
Apache Tomcat is an open-source web server and servlet container developed by
the Apache Software Foundation.
It provides a runtime environment for executing Java Servlets and JSP (Java
Server Pages).
Tomcat implements the Java Servlet and JSP specifications and acts as the
middleware between the client (browser) and the servlet/JSP program.

Purpose / Advantages of Tomcat:


1. Servlet & JSP Execution:
Provides a complete environment to execute servlets and JSP pages.
2. Open Source & Lightweight:
Freely available and ideal for local development or educational use.
3. Web Application Deployment:
Supports .war file deployment for easy packaging and distribution.
4. Cross-Platform:
Works on any OS with Java installed.
5. Supports Latest Java EE Standards:
Compatible with Servlet, JSP, and JDBC specifications.
6. Ease of Use:
Simple directory structure and quick configuration.

Detailed Working:
When a user requests a servlet through the browser (e.g.,
[Link] Tomcat performs the following
steps:
1. Receives the HTTP Request from the browser.
2. Checks [Link] or annotations for the servlet mapping.
3. Loads the Servlet Class if not already loaded.
4. Creates an Instance and calls the init() method.
5. For each client request, it calls the service() → doGet() or doPost()
methods.
6. Sends the HTTP Response (HTML output) back to the browser.
7. When the server shuts down, Tomcat calls the destroy() method of the
servlet.

5
Advanced Java and J2EE 23SCS052

Syntax (Directory Structure in Tomcat):


A servlet project in Tomcat follows this folder structure:
C:\apache-tomcat-10.1.0\webapps\MyApp\

├── [Link]
└── WEB-INF\
├── [Link]
└── classes\
└── [Link]

Code: Simple Servlet Example


File Name: [Link]
import [Link].*;
import [Link].*;
import [Link].*;

public class HelloServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {

[Link]("text/html");
PrintWriter out = [Link]();

[Link]("<html><body>");
[Link]("<h2>Welcome to Servlet Programming!</h2>");
[Link]("<p>This is a simple servlet running on Apache Tomcat.</p>");
[Link]("</body></html>");
}
}

Code Explanation:
1. Import Statements:
Import required servlet and I/O packages.
2. Extending HttpServlet:
The class inherits from HttpServlet to handle HTTP-based requests.
3. doGet() Method:
Responds to the client’s GET request (when a user accesses via browser
URL).
4. setContentType("text/html"):
Informs the browser that the response is in HTML format.
5. PrintWriter:
Used to send character text (HTML code) back to the client browser.

6
Advanced Java and J2EE 23SCS052

6. HTML Response:
The servlet dynamically generates the HTML output displayed to the user.

Important Methods:
Method Description
doGet() Handles GET requests (typical browser requests).
doPost() Handles POST requests (form submissions).
getWriter() Returns a PrintWriter object to write HTML output.
setContentType() Sets MIME type of response.
getParameter() Reads input values from client requests.
init() Initializes servlet once.
destroy() Destroys servlet instance on shutdown.

Configuration File: [Link]


The Deployment Descriptor ([Link]) defines servlet mappings.
<web-app>
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>

Explanation:
• <servlet> → defines the servlet.
• <servlet-class> → specifies class name.
• <url-pattern> → defines the URL path (used in browser to access servlet).

Steps to Execute Servlet in Tomcat:


1. Create a Web Application Folder under webapps (e.g., MyApp).
2. Write the Servlet Source File and compile it using [Link].
3. Place Compiled Class in WEB-INF/classes/.
4. Configure [Link] for servlet mapping.
5. Start Tomcat Server ([Link] or from IDE).
6. Access Servlet using:
7. [Link]

7
Advanced Java and J2EE 23SCS052

Example Output:
Welcome to Servlet Programming!
This is a simple servlet running on Apache Tomcat.

Example Explanation:
• The browser sends a request to the Tomcat server.
• Tomcat looks up the [Link] file and finds /welcome mapped to
HelloServlet.
• The container creates an instance of HelloServlet and executes doGet().
• The servlet sends an HTML response back to the browser.

Conclusion:
Tomcat is an essential servlet container that allows developers to test and deploy
Java-based web applications.
By configuring servlets inside Tomcat, web developers can process client
requests dynamically and produce real-time web content.
It is lightweight, powerful, and fully compliant with Java Servlet and JSP
specifications, making it the best environment for learning and deploying
Servlets.

Notes:
• Default Tomcat port: 8080
• [Link] is known as Deployment Descriptor.
• Servlet classes must be placed under WEB-INF/classes.
• Always restart Tomcat after making configuration changes.
• Tomcat versions (9, 10, etc.) support Servlet 4.0+ specifications.
• You can also use annotations instead of [Link]:
• @WebServlet("/welcome")

public class HelloServlet extends HttpServlet { ... }

The Servlet API and Packages ([Link], [Link]) and


Reading Servlet Parameters:

Definition:
The Servlet API is a set of interfaces and classes provided by Java to build server-
side web applications.

It defines how a servlet interacts with:


• the web container (Tomcat),
• the client (browser), and

8
Advanced Java and J2EE 23SCS052

• other components like request, response, and session objects.

The core API is divided into two main packages:


1. [Link] → Defines generic, protocol-independent classes and
interfaces.
2. [Link] → Extends [Link] to support HTTP-specific
requests and responses.

Purpose / Advantages:
1. Standardized Communication:
Provides consistent methods for handling client-server interaction.
2. Reusable Components:
Enables modular design through interfaces and abstract classes.
3. Protocol Independence:
The base [Link] package is protocol-agnostic.
4. Extensibility:
Developers can extend existing classes like HttpServlet.
5. Ease of Handling HTTP:
The [Link] package provides dedicated methods for GET,
POST, cookies, and sessions.
6. Integration:
Easily integrates with JSP, JDBC, and other Java EE technologies.

Detailed Working:
When a browser sends a request to a servlet:
1. The Servlet container converts the HTTP request into a HttpServletRequest
object.
2. It also creates a HttpServletResponse object to hold the response.
3. The container passes both objects to the servlet’s service() method.
4. The servlet reads data from HttpServletRequest (form fields, query
parameters).
5. It processes the request and writes the output to HttpServletResponse.
6. The container then sends the response back to the client browser.
Syntax:
The structure of a servlet using the Servlet API:
import [Link].*;
import [Link].*;
import [Link].*;

public class ExampleServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse


response)

9
Advanced Java and J2EE 23SCS052

throws ServletException, IOException {

[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<h3>Servlet API Example</h3>");
}
}

Code: Reading Servlet Parameters


Let’s take an example where a user submits a form and the servlet reads the form
parameters.
HTML Form ([Link]):
<form action="readparam" method="get">
Name: <input type="text" name="username"><br>
Email: <input type="text" name="email"><br>
<input type="submit" value="Submit">
</form>

Servlet Code ([Link]):


import [Link].*;
import [Link].*;
import [Link].*;

public class ReadParamServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {

[Link]("text/html");
PrintWriter out = [Link]();

// Reading parameters from request


String user = [Link]("username");
String mail = [Link]("email");

[Link]("<html><body>");
[Link]("<h2>User Details</h2>");
[Link]("<p>Name: " + user + "</p>");
[Link]("<p>Email: " + mail + "</p>");
[Link]("</body></html>");
}
}

10
Advanced Java and J2EE 23SCS052

Code Explanation:
1. getParameter(String name):
Reads the value of a form parameter from the client request.
2. Form Submission:
The browser sends the form data as a query string in the URL (for GET
method).
3. Dynamic Response:
Servlet displays the submitted information in HTML format.
4. Content Type:
setContentType("text/html") ensures browser renders HTML correctly.

Important Classes and Interfaces in Servlet API


Component Package Description
Main interface defining servlet lifecycle
Servlet [Link]
methods.
Abstract class providing protocol-
GenericServlet [Link]
independent implementation.
Provides HTTP-specific implementation
HttpServlet [Link]
of servlet.
Provides configuration data (init
ServletConfig [Link]
parameters).
Provides web application information
ServletContext [Link]
and environment.
ServletRequest [Link] Encapsulates client request information.
ServletResponse [Link] Encapsulates response sent to client.
Provides HTTP-specific request
HttpServletRequest [Link]
information.
Provides HTTP-specific response
HttpServletResponse [Link]
features.

Important Methods:
Method Belongs To Purpose
getParameter(String
HttpServletRequest Retrieves form parameter value.
name)
getParameterNames() HttpServletRequest Returns all parameter names.
getContentType() HttpServletResponse Sets MIME type of output.
Sends character output stream
getWriter() HttpServletResponse
to client.
getInputStream() HttpServletRequest Reads binary data from client.

11
Advanced Java and J2EE 23SCS052

Method Belongs To Purpose


getCookies() HttpServletRequest Retrieves cookies sent by client.
addCookie(Cookie c) HttpServletResponse Adds a cookie to the response.

Example: Reading Multiple Parameters


HTML Form ([Link]):
<form action="studentinfo" method="post">
Name: <input type="text" name="sname"><br>
Roll No: <input type="text" name="rollno"><br>
Course: <input type="text" name="course"><br>
<input type="submit" value="Submit">
</form>

Servlet Code ([Link]):


import [Link].*;
import [Link].*;
import [Link].*;

public class StudentInfo extends HttpServlet {


public void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {

[Link]("text/html");
PrintWriter out = [Link]();

String name = [Link]("sname");


String roll = [Link]("rollno");
String course = [Link]("course");

[Link]("<h3>Student Information</h3>");
[Link]("<p>Name: " + name + "</p>");
[Link]("<p>Roll No: " + roll + "</p>");
[Link]("<p>Course: " + course + "</p>");
}
}

Example Explanation:
1. Form Submission: User submits form data via POST request.
2. Request Handling: Servlet container creates HttpServletRequest and
HttpServletResponse objects.
3. Parameter Retrieval: The servlet reads data using getParameter().

12
Advanced Java and J2EE 23SCS052

4. Response Generation: Servlet sends a dynamically generated HTML page


showing user input.

Conclusion:
The Servlet API provides the foundation for all Java web applications.
The packages [Link] and [Link] simplify client-server
communication, allowing developers to easily read request parameters, generate
dynamic responses, and manage session information.
Understanding these classes and methods is essential for developing robust, data-
driven web applications.

Notes:
• The Servlet container automatically creates request and response objects
for each client request.
• HttpServletRequest → handles incoming data; HttpServletResponse →
handles outgoing data.
• doGet() is used for reading data (via URL), doPost() for sending form data.
• Always set response type using setContentType("text/html").
• Use getParameterNames() to loop through all request parameters
dynamically.
• Modern servlets may use annotations like @WebServlet("/readparam")
instead of [Link].

Handling HTTP Requests and Responses, Using Cookies, and Session


Tracking:

Definition:
HTTP (Hypertext Transfer Protocol) is a request–response communication
protocol used by web browsers and servers.
In Java Servlets, HTTP communication is managed through two key interfaces:
• HttpServletRequest → represents the client request.
• HttpServletResponse → represents the server response.
Together, they allow data transfer between the client (browser) and the web
server.
To maintain continuity between multiple client requests, Cookies and Session
Tracking mechanisms are used.

Purpose / Advantages:
1. Client–Server Communication:
Enables servlets to read client data and send responses dynamically.

13
Advanced Java and J2EE 23SCS052

2. Form Handling:
Helps in retrieving data from HTML forms and processing it server-side.
3. Dynamic Response Generation:
Responses are generated based on client input, cookies, or session data.
4. Session Management:
Maintains user state (login info, preferences) across multiple requests.
5. Data Persistence:
Cookies and sessions allow the server to remember user information
temporarily.
6. Secure Transactions:
Enables tracking and validation of user sessions in e-commerce or banking
apps.

Detailed Working:
When a user interacts with a web application:
1. The browser sends a request to the server (via GET or POST).
2. The Servlet container creates HttpServletRequest and
HttpServletResponse objects.
3. The servlet reads request parameters using [Link]().
4. The servlet sends a response using the response object (PrintWriter,
setContentType(), etc.).
5. To track user activity, the servlet can store data in:
o Cookies (stored on client browser).
o Sessions (stored on server).

Syntax:
Typical Servlet Handling HTTP Request and Response
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

[Link]("text/html");
PrintWriter out = [Link]();

String name = [Link]("username");


[Link]("<h3>Welcome, " + name + "!</h3>");
}

Code: Handling HTTP Request and Response


HTML Form ([Link]):
<form action="login" method="post">
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Login">

14
Advanced Java and J2EE 23SCS052

</form>

Servlet Code ([Link]):


import [Link].*;
import [Link].*;
import [Link].*;

public class LoginServlet extends HttpServlet {


public void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {

[Link]("text/html");
PrintWriter out = [Link]();

String user = [Link]("username");


String pass = [Link]("password");

if ([Link]("admin") && [Link]("1234")) {


[Link]("<h2>Login Successful!</h2>");
} else {
[Link]("<h2>Invalid Credentials</h2>");
}
}
}

Code Explanation:
1. getParameter() → Reads the input values from HTML form fields.
2. setContentType() → Informs browser about type of response (HTML).
3. PrintWriter → Sends dynamic content back to the client.
4. Conditional Logic → Validates credentials and displays result.
5. POST Method → Secures data as it is not visible in the URL.

Important Methods:
Method Belongs To Purpose
Reads client data from form
getParameter(String name) HttpServletRequest
field.
Retrieves HTTP header
getHeader(String name) HttpServletRequest
values.

15
Advanced Java and J2EE 23SCS052

Method Belongs To Purpose


Returns HTTP method
getMethod() HttpServletRequest
(GET/POST).
getCookies() HttpServletRequest Returns array of cookies.
Adds cookie to client
addCookie(Cookie c) HttpServletResponse
response.
Redirects client to another
sendRedirect(String url) HttpServletResponse
page.
setHeader(String name, String
HttpServletResponse Sets response header.
value)

Cookies:
Definition:
A Cookie is a small piece of information stored in the client’s browser by the
server.
Cookies help identify users during subsequent visits to a web application.

Purpose / Advantages:
• Maintains user data between multiple requests.
• Stores login preferences or session IDs.
• Reduces need to re-enter information.

Syntax:
Cookie cookie = new Cookie("username", "Shravya");
[Link](cookie);
Code Example ([Link]):
import [Link].*;
import [Link].*;
import [Link].*;

public class CookieDemo extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();

// Creating and sending cookie


Cookie user = new Cookie("username", "Shravya");
[Link](user);

[Link]("<h3>Cookie has been set successfully!</h3>");


16
Advanced Java and J2EE 23SCS052

}
}

Code Explanation:
1. The servlet creates a cookie with a name–value pair.
2. The cookie is added to the HTTP response.
3. The browser stores it and sends it back to the server on subsequent requests.

Example: Reading Cookies


Cookie[] cookies = [Link]();
for (Cookie c : cookies) {
[Link]("<p>" + [Link]() + ": " + [Link]() + "</p>");
}

Session Tracking
Definition:
Session tracking is a way to maintain a client’s state across multiple requests.
Unlike cookies, session data is stored on the server and linked using a unique
session ID.

Purpose / Advantages:
1. Maintains user data like username, cart items, etc.
2. More secure than cookies (server-side).
3. Supports login sessions and personalized experiences.

Syntax:
HttpSession session = [Link]();
[Link]("username", "Shravya");
String name = (String) [Link]("username");

Code Example ([Link]):


import [Link].*;
import [Link].*;
import [Link].*;

public class SessionDemo extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {

[Link]("text/html");
PrintWriter out = [Link]();

17
Advanced Java and J2EE 23SCS052

HttpSession session = [Link]();


[Link]("user", "Shravya");

[Link]("<h2>Session created successfully!</h2>");


[Link]("<p>Session ID: " + [Link]() + "</p>");
}
}

Example Explanation:
1. getSession() → Creates or retrieves a session for the current user.
2. setAttribute() → Stores data in the session object.
3. getId() → Returns unique session ID.
4. Session Lifetime: By default, lasts 30 minutes (configurable).

Important Session Methods:


Method Purpose
getSession() Creates or returns existing session.
getId() Returns unique session ID.
setAttribute(String, Object) Stores value in session.
getAttribute(String) Retrieves stored value.
invalidate() Destroys the session.
isNew() Checks if session is newly created.

Conclusion:
HTTP request and response handling form the foundation of client–server
communication in servlets.
Cookies and sessions help maintain user information across multiple web pages.
Cookies store data on the client side, while sessions keep it securely on the server,
ensuring a consistent and personalized experience.

Notes:
• HttpServletRequest and HttpServletResponse are automatically provided
by the container.
• Cookies are limited in size (around 4 KB).
• Session timeout can be configured using [Link].
• Sessions are destroyed automatically after timeout or logout.
• Use sessions for sensitive data (like login info) and cookies for non-
sensitive preferences.

18
Advanced Java and J2EE 23SCS052

Java Server Pages (JSP) – Introduction, Tags, and Architecture:


Definition:
Java Server Pages (JSP) is a server-side technology used to create dynamic web
content by combining HTML, Java code, and special JSP tags.
JSP is an extension of the Servlet technology that simplifies the process of
building dynamic web pages.
It allows embedding Java code directly into HTML pages using JSP scripting
elements.

Purpose / Advantages of JSP:


1. Simplifies Dynamic Web Development:
Developers can write HTML and Java code together.
2. Reduces Servlet Complexity:
JSPs are easier to maintain since presentation logic (HTML) and business
logic (Java) are separated.
3. Automatic Translation:
Each JSP page is automatically compiled into a servlet by the web
container (like Tomcat).
4. Reusable Components:
Supports JavaBeans, custom tags, and EL (Expression Language) for
modular design.
5. Integration with Servlets:
JSP and Servlets work together using the MVC pattern (Model–View–
Controller).
6. Portable and Scalable:
Platform-independent and runs in any Java EE–compliant container.

Detailed Working:
When a JSP page is requested:
1. The client browser sends a request to the server (e.g., [Link]).
2. The JSP engine in the server translates the JSP into a Java servlet.
3. The generated servlet is compiled into a .class file.
4. The servlet executes, producing dynamic HTML output.
5. The response is sent back to the client browser.
Subsequent requests to the same JSP use the already compiled servlet (for
performance).

Syntax (Basic JSP Page):


<%@ page language="java" contentType="text/html" %>
<html>
<head><title>Welcome JSP</title></head>
<body>
<h2>Welcome to Java Server Pages!</h2>

19
Advanced Java and J2EE 23SCS052

<p>Current Time: <%= new [Link]() %></p>


</body>
</html>

Code: Simple JSP Example


File: [Link]
<%@ page language="java" contentType="text/html" %>
<html>
<head><title>JSP Example</title></head>
<body>
<h2>Welcome User!</h2>
<%
String name = "Shravya";
[Link]("<p>Hello, " + name + "! This is your first JSP page.</p>");
%>
</body>
</html>

Code Explanation:
1. <%@ page %> → Directive to define page attributes like language and
content type.
2. <% %> → Scriptlet tag; used to write Java code inside HTML.
3. [Link]() → Sends output to the client’s browser.
4. The JSP container converts this page into a servlet automatically.
5. The compiled servlet generates the HTML response dynamically.

Important JSP Tags:


Tag Type Syntax Purpose
Directive <%@ directive Defines page-level settings. Example:
Tag attribute="value" %> <%@ page import="[Link].*" %>
Declaration Declares variables or methods at class
<%! code %>
Tag level.
Contains Java code executed during
Scriptlet Tag <% code %>
request.
Expression Outputs the result of a Java expression to
<%= expression %>
Tag the browser.
Comment JSP-specific comment, not visible in
<%-- comment --%>
Tag HTML source.

Example of All JSP Tags:


<%@ page import="[Link].*" %>
<html>
20
Advanced Java and J2EE 23SCS052

<body>
<%! int count = 0; %>
<%
count++;
String name = "Radhya";
%>
<h3>Welcome <%= name %></h3>
<p>This page has been visited <%= count %> times.</p>
<%-- This is a JSP comment --%>
</body>
</html>

Example Explanation:
1. <%! %> declares a variable that persists across requests.
2. <% %> increments the counter for each visit.
3. <%= %> displays dynamic data directly in the output.
4. The JSP engine processes and translates the page into a servlet that outputs
the final HTML.

Important Methods (in Implicit Objects):


Object Class Purpose
request HttpServletRequest Used to read client data.
response HttpServletResponse Used to send output to the browser.
out JspWriter Used to write content to response.
session HttpSession Used to track user sessions.
application ServletContext Shares data among all JSP pages.
config ServletConfig Provides configuration info.
exception Throwable Used in error pages.

Example: JSP Page Using Implicit Objects


<%@ page language="java" contentType="text/html" %>
<html>
<body>
<h2>Using JSP Implicit Objects</h2>
<p>Session ID: <%= [Link]() %></p>
<p>Server Info: <%= [Link]() %></p>
</body>
</html>

Example Explanation:
• [Link]() → Returns the current user’s session ID.

21
Advanced Java and J2EE 23SCS052

• [Link]() → Returns server details (e.g., Apache Tomcat


version).
• These objects are automatically available in every JSP — no import or
declaration needed.

Conclusion:
JSP simplifies web application development by integrating HTML and Java
seamlessly.
It provides an easy way to build dynamic pages while maintaining flexibility and
scalability.
JSP pages are automatically converted into servlets, making them powerful and
efficient for modern web applications.

Notes:
• JSP = HTML + Java + Tags.
• JSPs are translated into servlets during the first request.
• Use JSP for presentation and Servlets for business logic (MVC pattern).
• JSPs can access JavaBeans, custom tags, and databases via JDBC.
• Common implicit objects: request, response, out, session, application,
config.
• JSP pages have .jsp extension and are deployed inside the Tomcat webapps
folder.

JSP Objects – Request, Response, Session, Cookies, and Scripting Elements:

Definition:
In Java Server Pages (JSP), several implicit objects are automatically available
for developers to use without explicit declaration or import.
These objects represent key components of a web application, such as client
requests, server responses, user sessions, and cookies.
Additionally, scripting elements allow embedding Java code directly into JSP
pages for dynamic content generation.

Purpose / Advantages:
1. Simplifies Coding:
No need to create objects manually; JSP provides them automatically.
2. Dynamic Content Generation:
Allows processing user input, generating output, and maintaining session
data easily.
3. Easy State Management:
session and cookie objects enable data tracking across multiple pages.

22
Advanced Java and J2EE 23SCS052

4. Seamless Communication:
request and response objects manage client–server interactions efficiently.
5. Embedded Logic:
Scripting elements let developers add Java code into HTML directly.
6. Reusability and Maintainability:
Commonly used data and methods are available globally within a JSP page.

Detailed Working:
When a user requests a JSP page:
1. The web container creates implicit objects such as request, response,
session, and out.
2. These objects are made available to the JSP page for handling data and user
interactions.
3. Developers can use scripting elements to process inputs and dynamically
produce HTML content.
4. The container handles the conversion of JSP to servlet, ensuring these
objects function like in a servlet environment.

1. request Object
Definition:
The request object is an instance of HttpServletRequest that holds client request
data, including parameters, headers, and attributes.

Syntax:
<%= [Link]("username") %>

Code Example:
HTML Form ([Link]):
<form action="[Link]" method="get">
Name: <input type="text" name="username"><br>
<input type="submit" value="Submit">
</form>
JSP File ([Link]):
<html>
<body>
<h2>User Information</h2>
<p>Hello, <%= [Link]("username") %></p>
</body>
</html>

Explanation:
• Reads the form field “username” from the client’s request.
• Displays the value dynamically on the page.

23
Advanced Java and J2EE 23SCS052

Important Methods:
Method Description
getParameter(String) Reads form field value.
getParameterNames() Returns all parameter names.
getHeader(String) Returns header info.
getMethod() Returns HTTP method (GET/POST).

2. response Object
Definition:
The response object is an instance of HttpServletResponse used to send output or
data from the server to the client browser.

Syntax:
<%
[Link]("text/html");
[Link]("Response generated successfully!");
%>

Example:
<%@ page language="java" contentType="text/html" %>
<html>
<body>
<%
[Link]("Refresh", "5");
[Link]("<h3>This page will refresh every 5 seconds</h3>");
%>
</body>
</html>

Explanation:
• The response object is used to set response type, headers, and cookies, or
redirect users.

Important Methods:
Method Purpose
setContentType(String type) Sets response type.
sendRedirect(String url) Redirects to another page.
addCookie(Cookie c) Adds cookie to response.
setHeader(String, String) Sets HTTP header.

24
Advanced Java and J2EE 23SCS052

3. session Object
Definition:
The session object is an instance of HttpSession used to store user-specific data
across multiple pages during a session.

Syntax:
<%
[Link]("user", "Shravya");
String name = (String) [Link]("user");
[Link]("Welcome " + name);
%>

Example:
<%@ page language="java" contentType="text/html" %>
<html>
<body>
<%
[Link]("email", "shravya@[Link]");
[Link]("Session ID: " + [Link]());
%>
</body>
</html>

Explanation:
• A session is automatically created for each user.
• Data stored in session persists across multiple requests.

Important Methods:
Method Purpose
setAttribute(String, Object) Stores data in session.
getAttribute(String) Retrieves stored value.
getId() Returns session ID.
invalidate() Destroys session.
isNew() Checks if session is new.

4. cookie Object
Definition:
A cookie is a small data file stored on the client-side that helps in tracking user
identity and preferences.

Syntax:
<%
25
Advanced Java and J2EE 23SCS052

Cookie user = new Cookie("username", "Shravya");


[Link](user);
%>

Example:
<%@ page import="[Link]" %>
<html>
<body>
<%
Cookie cookie = new Cookie("user", "Radhya");
[Link](cookie);
[Link]("Cookie created successfully!");
%>
</body>
</html>

Explanation:
• The server creates a cookie and sends it to the client browser.
• Browser returns the cookie with subsequent requests.

Important Methods:
Method Description
getName() Returns cookie name.
getValue() Returns cookie value.
setMaxAge(int) Sets cookie expiration time.
addCookie(Cookie) Adds cookie to HTTP response.

5. JSP Scripting Elements


Definition:
Scripting elements allow Java code to be embedded directly into HTML content
within a JSP page.
These elements are used to add dynamic functionality, control flow, or declare
variables.

Types of Scripting Elements:


Type Syntax Purpose
Declaration Tag <%! code %> Declares methods or variables.
Contains Java statements executed at
Scriptlet Tag <% code %>
runtime.
Expression Tag <%= expression %> Outputs the result of an expression.

26
Advanced Java and J2EE 23SCS052

Example:
<%@ page language="java" contentType="text/html" %>
<html>
<body>
<%! int count = 0; %>
<%
count++;
String user = "Shravya";
%>
<h3>Welcome <%= user %></h3>
<p>This page has been visited <%= count %> times.</p>
</body>
</html>

Explanation:
1. <%! %> declares a variable that persists across requests.
2. <% %> executes Java code at runtime.
3. <%= %> directly prints dynamic output to the page.

Conclusion:
JSP provides built-in implicit objects like request, response, session, and cookie
that simplify client–server interaction.
They make JSP powerful for handling dynamic data, user tracking, and
communication between pages.
With scripting elements, developers can embed Java logic directly into HTML to
generate dynamic, user-specific web pages easily.

Notes:
• JSP implicit objects are created by the container automatically.
• Cookies are stored on the client; sessions are stored on the server.
• Use [Link]() to log out a user.
• Avoid heavy Java logic in JSP; use Servlets for processing and JSP for
presentation (MVC model).
• JSP scripting elements should be used carefully to keep pages readable and
maintainable.

Java Database Connectivity (JDBC): Concept, Driver Types, Packages, and


Database Connectivity:

Definition:
Java Database Connectivity (JDBC) is an API (Application Programming
Interface) in Java that enables communication between Java applications and

27
Advanced Java and J2EE 23SCS052

databases.
It allows developers to connect, query, update, and manage databases using
standard Java code, regardless of the database vendor.
JDBC acts as a bridge between Java programs and database systems such as
MySQL, Oracle, or SQL Server.

Purpose / Advantages of JDBC:


1. Database Independence:
Works with any relational database that provides a JDBC driver.
2. Platform Independent:
Written in Java, so it runs on any platform supporting Java.
3. Standardized API:
Provides consistent methods for connecting and manipulating databases.
4. Secure and Scalable:
Handles transactions, exceptions, and secure data access efficiently.
5. Supports SQL Commands:
Allows execution of SQL queries (SELECT, INSERT, UPDATE,
DELETE).
6. Integration:
Can be easily integrated with Servlets, JSP, and enterprise applications.

Detailed Working:
The JDBC architecture consists of:
1. JDBC API: Provides interfaces and classes for database operations.
2. JDBC Driver Manager: Manages different database drivers.
3. JDBC Driver: Translates Java calls into database-specific calls.
4. Database: Stores and retrieves data as requested.
JDBC Workflow:
1. Load the Driver – Register the database driver.
2. Establish Connection – Use DriverManager to connect to the database.
3. Create Statement – Prepare SQL queries.
4. Execute Query – Send SQL commands to the database.
5. Process Results – Retrieve and display data using ResultSet.
6. Close Connection – Release database resources.

Syntax:
import [Link].*;
class JDBCExample {
public static void main(String args[]) throws Exception {
// Step 1: Load Driver
[Link]("[Link]");

// Step 2: Establish Connection

28
Advanced Java and J2EE 23SCS052

Connection con = [Link](


"jdbc:mysql://localhost:3306/college", "root", "password");

// Step 3: Create Statement


Statement stmt = [Link]();

// Step 4: Execute Query


ResultSet rs = [Link]("SELECT * FROM student");

// Step 5: Process Result


while ([Link]()) {
[Link]([Link](1) + " " + [Link](2));
}

// Step 6: Close Connection


[Link]();
}
}

Code Explanation:
1. [Link]() → Loads the JDBC driver class into memory.
2. [Link]() → Establishes a connection with the
database.
3. createStatement() → Creates a statement object to send SQL queries.
4. executeQuery() → Executes the SQL SELECT query.
5. ResultSet → Retrieves the data returned by the query.
6. close() → Closes the connection and releases resources.
JDBC Driver Types:
Type Name Description Example
JDBC–ODBC Uses ODBC driver to [Link]
Type 1
Bridge Driver connect to database. er
Native–API Converts JDBC calls into
Type 2 Oracle OCI Driver
Driver native API calls.
Network Uses middleware server to
Type 3 IDS Server
Protocol Driver translate JDBC calls.
Thin Driver Directly connects Java to MySQL Connector/J, Oracle
Type 4
(Pure Java) database using socket. Thin Driver

Note:
Type 4 is the most widely used because it’s pure Java, fast, and platform-
independent.

29
Advanced Java and J2EE 23SCS052

Important JDBC Packages:


Package
Purpose
Name
Contains core JDBC interfaces and classes like Connection,
[Link]
Statement, ResultSet, DriverManager.
Contains advanced features like connection pooling and distributed
[Link]
transactions.

Important JDBC Classes and Interfaces:


Class / Interface Description
DriverManager Manages JDBC drivers and database connections.
Connection Represents a connection session with a database.
Statement Used to send SQL commands to the database.
PreparedStatement Precompiled SQL statements for repeated execution.
ResultSet Represents the data retrieved from the database.
SQLException Handles database access errors and exceptions.

Example: Inserting Data into Database


import [Link].*;

public class InsertDemo {


public static void main(String[] args) {
try {
[Link]("[Link]");
Connection con = [Link](
"jdbc:mysql://localhost:3306/college", "root", "password");

PreparedStatement ps = [Link](
"INSERT INTO student (rollno, name, marks) VALUES (?, ?, ?)");

[Link](1, 101);
[Link](2, "Shravya");
[Link](3, 95);

int result = [Link]();


[Link](result + " record(s) inserted.");

[Link]();
} catch (Exception e) {
[Link](e);
}
30
Advanced Java and J2EE 23SCS052

}
}

Code Explanation:
1. PreparedStatement → Prevents SQL injection and allows parameterized
queries.
2. setInt() / setString() → Sets parameter values dynamically.
3. executeUpdate() → Executes INSERT, UPDATE, DELETE statements.
4. Output: Displays confirmation of the number of records inserted.

Transaction Processing:
Transactions ensure data consistency and reliability during multiple database
operations.

Example:
[Link](false); // Disable auto-commit
[Link]("INSERT INTO student VALUES(102, 'Radhya', 90)");
[Link](); // Commit changes
If an error occurs:
[Link](); // Undo changes

Metadata and Data Types:


1. Metadata:
Metadata provides information about the database and its structure.
• DatabaseMetaData → Info about database.
• ResultSetMetaData → Info about columns in the result set.

Example:
DatabaseMetaData dbmd = [Link]();
[Link]("Driver Name: " + [Link]());

2. Data Types:
JDBC supports mapping between SQL data types and Java data types, such
as:

SQL Type Java Type


VARCHAR String
INTEGER int
FLOAT float
DATE [Link]
BOOLEAN boolean

31
Advanced Java and J2EE 23SCS052

Exceptions in JDBC:
Exception Type Description
SQLException General database access error.
SQLSyntaxErrorException SQL query syntax problem.
SQLTimeoutException Query or connection timeout.
BatchUpdateException Error during batch updates.

Example:
catch(SQLException e) {
[Link]("Error: " + [Link]());
}

Conclusion:
JDBC provides a robust and flexible interface for interacting with databases using
Java.
By following the JDBC steps—loading driver, establishing connection, executing
SQL, and handling results—developers can perform efficient database
operations.
With the use of PreparedStatement, ResultSet, and Transaction handling, JDBC
ensures secure, reliable, and portable database connectivity.

Notes:
• Always close connections ([Link]()) to avoid memory leaks.
• Use PreparedStatement instead of Statement for efficiency.
• Use connection pooling (from [Link]) in enterprise applications.
• JDBC is part of the Java Standard Edition (JSE) since JDK 1.1.
• Latest JDBC versions support modern databases like PostgreSQL,
MongoDB (through drivers).

JDBC Processing – ResultSet, Transaction Management, and Exception


Handling:

Definition:
JDBC Processing refers to the series of operations performed while interacting
with a database through the JDBC API.
This includes retrieving data, navigating results, updating records, and ensuring
data consistency through transactions.
To handle runtime issues effectively, JDBC provides robust exception handling
mechanisms via the SQLException class.

32
Advanced Java and J2EE 23SCS052

Purpose / Advantages:
1. Efficient Data Access:
Enables retrieval and manipulation of data directly from Java programs.
2. Transactional Integrity:
Ensures that a group of database operations is executed as a single unit.
3. Error Handling:
Provides systematic exception management to maintain data reliability.
4. Data Consistency:
Prevents partial updates or corrupt data through commit and rollback
mechanisms.
5. Flexible Navigation:
ResultSet allows forward, backward, and random access to retrieved data.
6. Security and Performance:
PreparedStatement and transaction management prevent SQL injection and
optimize queries.

Detailed Working:
A typical JDBC process involves:
1. Establishing a Connection – Connect to the database using DriverManager.
2. Executing SQL Statements – Use Statement or PreparedStatement.
3. Processing Results – Handle the output via ResultSet.
4. Managing Transactions – Commit or rollback changes to ensure data
integrity.
5. Handling Exceptions – Use SQLException for managing runtime errors
gracefully.
6. Closing Connections – Release all database resources after completion.

1. ResultSet
Definition:
A ResultSet is a table of data returned by executing a SQL query using Statement
or PreparedStatement.
It maintains a cursor that points to the current row in the result.

Syntax:
ResultSet rs = [Link]("SELECT * FROM student");

Code Example:
import [Link].*;

public class ResultSetDemo {


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

33
Advanced Java and J2EE 23SCS052

Connection con = [Link](


"jdbc:mysql://localhost:3306/college", "root", "password");

Statement stmt = [Link]();


ResultSet rs = [Link]("SELECT * FROM student");

while ([Link]()) {
[Link]("Roll No: " + [Link]("rollno"));
[Link]("Name: " + [Link]("name"));
[Link]("Marks: " + [Link]("marks"));
[Link]("--------------------------");
}

[Link]();
} catch (Exception e) {
[Link](e);
}
}
}

Code Explanation:
1. executeQuery() executes a SQL SELECT statement and returns a
ResultSet.
2. [Link]() moves the cursor to the next record.
3. getInt() and getString() retrieve data from the columns.
4. The loop continues until all records are processed.

Important Methods in ResultSet:


Method Description
next() Moves cursor to next row.
previous() Moves cursor to previous row.
first() / last() Moves to first or last row.
getInt(column) Retrieves integer value.
getString(column) Retrieves string value.
updateRow() Updates current row in the database.
close() Closes the ResultSet.

Types of ResultSet:
Type Description
TYPE_FORWARD_ONLY Default type; moves forward only.

34
Advanced Java and J2EE 23SCS052

Type Description
Can scroll in both directions; not sensitive to
TYPE_SCROLL_INSENSITIVE
changes.
TYPE_SCROLL_SENSITIVE Reflects changes made by others while open.

Creation Example:
Statement stmt = [Link](
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);

2. Transaction Management
Definition:
A transaction is a group of one or more SQL statements executed as a single unit
of work.
Either all operations succeed (commit) or none of them take effect (rollback) —
ensuring atomicity and data consistency.

Purpose:
• To maintain data integrity in case of system or network failures.
• To prevent partial updates in multi-step operations.
• To handle banking or inventory scenarios where atomicity is crucial.

Syntax:
[Link](false); // Disable auto-commit
[Link]("INSERT INTO student VALUES(103, 'Radhya', 88)");
[Link](); // Commit changes
Code Example:
import [Link].*;

public class TransactionDemo {


public static void main(String[] args) {
try {
[Link]("[Link]");
Connection con = [Link](
"jdbc:mysql://localhost:3306/college", "root", "password");

[Link](false); // Disable auto-commit

Statement stmt = [Link]();


[Link]("INSERT INTO student VALUES(104, 'Shravya',
92)");

35
Advanced Java and J2EE 23SCS052

[Link]("UPDATE student SET marks = 100 WHERE rollno


= 104");

[Link](); // Commit both queries


[Link]("Transaction committed successfully!");

[Link]();
} catch (Exception e) {
[Link](e);
}
}
}

Code Explanation:
1. setAutoCommit(false) → Turns off auto-commit, allowing manual
transaction control.
2. executeUpdate() → Executes SQL statements.
3. commit() → Confirms all operations permanently.
4. If Error Occurs: The developer can call rollback() to revert changes.

Example with Rollback:


try {
[Link](false);
[Link]("INSERT INTO student VALUES(105, 'Aarav', 89)");
[Link]("DELETE FROM student WHERE rollno = 101");

// Suppose error occurs here


[Link](); // Undo all changes
[Link]("Transaction rolled back!");
} catch (SQLException e) {
[Link]();
}

Important Transaction Methods:


Method Purpose
setAutoCommit(false) Disables auto-commit mode.
commit() Confirms changes made by SQL statements.
rollback() Reverts all changes since last commit.
setSavepoint() Creates a rollback checkpoint.
releaseSavepoint() Removes a savepoint.

36
Advanced Java and J2EE 23SCS052

3. Exception Handling in JDBC


Definition:
Exception handling ensures that the application handles database errors
gracefully without crashing.
In JDBC, exceptions are mainly of type SQLException.

Code Example:
import [Link].*;

public class ExceptionDemo {


public static void main(String[] args) {
try {
[Link]("[Link]");
Connection con = [Link](
"jdbc:mysql://localhost:3306/college", "root", "wrongpass");

Statement stmt = [Link]();


[Link]("SELECT * FROM non_existing_table");
}
catch (SQLException e) {
[Link]("SQL Error: " + [Link]());
[Link]("SQL State: " + [Link]());
[Link]("Error Code: " + [Link]());
}
catch (Exception e) {
[Link]("General Error: " + e);
}
}
}

Code Explanation:
1. SQLException is caught if there’s a database access issue.
2. getMessage() → Returns error details.
3. getSQLState() → Provides SQL state code (vendor-specific).
4. getErrorCode() → Returns numeric error code.
5. catch(Exception) → Catches other general runtime errors.

Common JDBC Exceptions:


Exception Description
SQLException General database access error.
SQLTimeoutException Query execution time exceeded.
SQLSyntaxErrorException Syntax error in SQL statement.

37
Advanced Java and J2EE 23SCS052

Exception Description
Primary key or foreign key
SQLIntegrityConstraintViolationException
violation.
BatchUpdateException Error during batch operations.

Conclusion:
JDBC processing is the core mechanism that enables Java applications to
communicate with databases efficiently.
By using ResultSet, developers can retrieve and manipulate data; through
transactions, they ensure data integrity; and with exception handling, they
maintain robust, error-free programs.
Together, these features make JDBC a powerful and reliable framework for
enterprise-level data-driven applications.

Notes:
• Always close ResultSet, Statement, and Connection objects.
• Use try-with-resources in modern Java to auto-close connections.
• Combine transactions with PreparedStatements for maximum reliability.
• Logging exceptions using frameworks like Log4j helps in debugging.
• Transaction management is vital in banking, order processing, and ERP
systems.

Metadata, Data Types, and Overall JDBC Summary:

Definition:
In JDBC, Metadata refers to data about data — that is, information about the
structure of the database, its tables, columns, supported SQL features, and driver
details.
It helps developers discover database properties dynamically during runtime
without manually checking the database schema.
In addition, data type mapping in JDBC ensures that SQL data types from the
database are correctly translated into equivalent Java data types, enabling smooth
communication between Java and the database.

Purpose / Advantages:
1. Dynamic Database Exploration:
Allows retrieval of table names, column names, and data types at runtime.
2. Driver and Connection Info:
Helps in checking the capabilities of the JDBC driver and database product
details.

38
Advanced Java and J2EE 23SCS052

3. Automated Application Development:


Metadata enables creation of tools that can adapt automatically to database
structure changes.
4. Error Reduction:
Helps verify SQL queries and table structures before execution.
5. Type Safety:
Ensures correct mapping between SQL and Java data types, preventing
runtime conversion errors.
6. Performance Optimization:
Developers can optimize queries by understanding the database’s
supported features and limits.

Detailed Working:
Metadata in JDBC is provided through three main interfaces:
1. DatabaseMetaData – Provides information about the database as a whole.
2. ResultSetMetaData – Provides information about the result set returned by
a query.
3. ParameterMetaData – Provides information about the parameters in a
PreparedStatement.

1. DatabaseMetaData
Definition:
The DatabaseMetaData interface gives information about the database system
and JDBC driver being used.

Syntax:
DatabaseMetaData dbmd = [Link]();

Code Example:
import [Link].*;

public class DatabaseMetaDataDemo {


public static void main(String[] args) throws Exception {
[Link]("[Link]");
Connection con = [Link](
"jdbc:mysql://localhost:3306/college", "root", "password");

DatabaseMetaData dbmd = [Link]();

[Link]("Database Product Name: " +


[Link]());
[Link]("Database Version: " +
[Link]());

39
Advanced Java and J2EE 23SCS052

[Link]("Driver Name: " + [Link]());


[Link]("URL: " + [Link]());
[Link]("User Name: " + [Link]());

[Link]();
}
}

Explanation:
• getDatabaseProductName() → Returns the name of the database (e.g.,
MySQL).
• getDriverName() → Returns the name of the JDBC driver.
• getUserName() → Displays the current database user.
• getURL() → Returns the connection URL string.

Important Methods in DatabaseMetaData:


Method Description
getDatabaseProductName() Returns the name of the database product.
getDatabaseProductVersion() Returns the version number of the database.
getDriverName() Returns the name of the JDBC driver.
getUserName() Returns username of current connection.
getTables() Returns list of tables in database.
getSchemas() Returns available schemas.

2. ResultSetMetaData
Definition:
The ResultSetMetaData interface provides information about the structure of the
ResultSet, such as number of columns, column names, and their data types.

Syntax:
ResultSetMetaData rsmd = [Link]();

Code Example:
import [Link].*;

public class ResultSetMetaDataDemo {


public static void main(String[] args) throws Exception {
[Link]("[Link]");
Connection con = [Link](
"jdbc:mysql://localhost:3306/college", "root", "password");

40
Advanced Java and J2EE 23SCS052

Statement stmt = [Link]();


ResultSet rs = [Link]("SELECT * FROM student");

ResultSetMetaData rsmd = [Link]();


int columnCount = [Link]();

[Link]("Number of Columns: " + columnCount);


for (int i = 1; i <= columnCount; i++) {
[Link]("Column " + i + ": " + [Link](i)
+ " (" + [Link](i) + ")");
}

[Link]();
}
}

Explanation:
• getColumnCount() → Returns number of columns in ResultSet.
• getColumnName() → Returns column name.
• getColumnTypeName() → Returns SQL data type of each column.

Important Methods in ResultSetMetaData:


Method Description
getColumnCount() Returns total number of columns.
getColumnName(int) Returns the name of specified column.
getColumnTypeName(int) Returns SQL data type of the column.
getTableName(int) Returns table name for the specified column.
isNullable(int) Checks if column allows NULL values.

3. ParameterMetaData
Definition:
The ParameterMetaData interface provides information about the number, type,
and properties of parameters in a PreparedStatement.

Syntax:
ParameterMetaData pmd = [Link]();

Example:
PreparedStatement ps = [Link](
"INSERT INTO student VALUES (?, ?, ?)");
ParameterMetaData pmd = [Link]();
[Link]("Parameter Count: " + [Link]());
41
Advanced Java and J2EE 23SCS052

4. Data Types in JDBC


Definition:
JDBC data types map SQL data types from the database to equivalent Java data
types.
This mapping ensures type compatibility between SQL tables and Java variables.

SQL-to-Java Data Type Mapping:


SQL Data Type Java Equivalent Type Example
CHAR, VARCHAR String Student name
INTEGER int Roll number
FLOAT, DOUBLE float / double Marks
DECIMAL BigDecimal Salary
DATE [Link] DOB
TIME [Link] Login time
BOOLEAN boolean Status flag
BLOB [Link] Binary data (images)

Example: Retrieving Data with Type Mapping


ResultSet rs = [Link]("SELECT rollno, name, marks, dob FROM
student");
while ([Link]()) {
int roll = [Link]("rollno");
String name = [Link]("name");
float marks = [Link]("marks");
Date dob = [Link]("dob");

[Link](roll + " | " + name + " | " + marks + " | " + dob);
}

Explanation:
• getInt() maps SQL INTEGER to Java int.
• getString() maps SQL VARCHAR to Java String.
• getFloat() maps SQL FLOAT to Java float.
• getDate() maps SQL DATE to [Link].

5. Exception Handling for Metadata and Data Types


Since metadata and data type operations involve database access, they can throw
SQLException.

Always use try-catch blocks to handle exceptions.

42
Advanced Java and J2EE 23SCS052

catch (SQLException e) {
[Link]("Error accessing metadata: " + [Link]());
}

Conclusion:
Metadata provides vital information about the database schema, tables, columns,
and driver configuration, allowing programs to adapt dynamically to database
structures.
Meanwhile, data type mapping ensures seamless conversion between SQL and
Java types, facilitating smooth data communication.
Together, they enhance the flexibility, reliability, and efficiency of JDBC-based
applications.

Notes:
• DatabaseMetaData is retrieved from Connection objects.
• ResultSetMetaData is retrieved from ResultSet objects.
• ParameterMetaData is retrieved from PreparedStatement objects.
• Always close connections and handle exceptions properly.
• Use metadata for database introspection in enterprise systems and database
tools.
• SQL–Java type mapping is automatically handled by JDBC but can be
customized if needed.
• Common JDBC drivers: MySQL Connector/J, Oracle Thin Driver,
PostgreSQL Driver.

43

Common questions

Powered by AI

A servlet can handle multiple form parameters by using the getParameter method provided by the HttpServletRequest interface. This method allows the servlet to retrieve the values of individual form parameters by their name, facilitating the processing of user input sent via HTML forms. In cases where you need to handle multiple parameters dynamically, the getParameterNames method can be used to iterate over all parameter names submitted in the request. This process is crucial for applications that require form data processing, hence enhancing the ability to generate customized dynamic responses based on user inputs .

In JDBC, transaction management ensures data integrity by treating a series of SQL operations as a single unit of work, thereby guaranteeing that either all operations within the transaction succeed or none are applied in case of failure. This is achieved using methods like setAutoCommit(false), which disables auto-commit mode, allowing the developer to control exactly when changes are committed using commit() or rolled back with rollback() in the event of an error. These mechanisms prevent partial updates and maintain consistency even amidst issues, which is critical in scenarios such as banking transactions or inventory adjustments .

Failure to close JDBC connections can lead to resource leaks, exhausting database resource limits and potentially crashing applications due to the scarcity of available connections. Not closing connections also increases the risk of memory leaks, impacting application performance negatively. Modern Java mitigates this issue through practices like using the try-with-resources statement, which automatically closes JDBC resources like Connection, ResultSet, and Statement after use. Additionally, techniques such as connection pooling help manage connections efficiently, ensuring that resources are reused and maintained optimally .

The Java Servlet API offers several advantages in web application development. These include standardized communication, which provides consistent methods for handling client-server interactions; reusable components through interfaces and abstract classes, promoting modular design; and protocol independence, allowing for base servlet implementations without protocol specificity. The API also supports extensibility, enabling developers to extend existing classes like HttpServlet, and ease in handling HTTP requests through dedicated methods for GET, POST, session management, etc. Additionally, its integration capability with JSP, JDBC, and other Java EE technologies enhances its versatility .

The Servlet container manages the lifecycle of a servlet by first loading and instantiating the servlet class. When a request arrives, it creates HttpServletRequest and HttpServletResponse objects and invokes the servlet's service() method, passing these objects. The servlet processes the request data and generates a dynamic response, writing to the HttpServletResponse. Finally, the response is sent back to the client through the container. The container may also manage servlet destruction, freeing resources and handling cleanup when a servlet is no longer needed, ensuring efficient management of web application components .

PreparedStatement is preferred over Statement in JDBC due to its security and performance benefits. It helps in preventing SQL injection attacks by precompiling the SQL statement and allowing parameterized queries, which makes it harder for attackers to inject malicious SQL code. Performance-wise, PreparedStatements allow for the execution plan of queries to be reused by the database, reducing the overhead associated with parsing and compiling SQL on every execution. These advantages make PreparedStatement a more robust choice for executing SQL queries, particularly in applications with security and efficiency demands .

Annotations like @WebServlet simplify the deployment and configuration of Java Servlets by allowing metadata to be embedded directly in the source code. This negates the need for separate configuration files like web.xml, making the process more straightforward and less error-prone. Developers can quickly map servlet classes to URL patterns directly in the code, which improves code readability and maintenance. Annotations also support modern development practices and improve the scalability of applications by reducing the configuration overhead .

The HttpServletRequest and HttpServletResponse interfaces are crucial for HTTP communication in Java Servlets as they encapsulate all the information related to a client request and its resulting server response. HttpServletRequest allows the servlet to read data from HTTP requests, including form fields, query parameters, and headers. HttpServletResponse, on the other hand, facilitates the servlet in sending information back to the client, managing content types, and implementing dynamic content rendering using methods like getWriter() and setContentType(“text/html”). Together, they allow seamless data transfer and dynamic response generation in web applications .

Cookies and session tracking are essential for maintaining continuity across multiple client requests in web applications. Cookies, stored on the client-side, can hold user-specific data, ensuring that subsequent requests are identifiable and associated with past interactions. Session tracking, managed server-side, maintains user state between requests, allowing for information like login credentials, shopping cart data, or user preferences to persist throughout the browsing session. Both mechanisms are pivotal for user experience and application functionality, especially in scenarios where secure, stateful interactions are crucial .

The ResultSet interface in JDBC provides a programmatic way to interact with the data retrieved from a database query. Its features include navigating through the data using methods like next(), previous(), first(), and last() which move the cursor against the records in various directions. The interface also facilitates data retrieval via methods such as getInt(column), getString(column), and updateRow(), allowing developers to manipulate and update data directly through the ResultSet. ResultSet's design supports flexible data access patterns, making it integral for database read operations .

You might also like