java unit 1
java unit 1
1. Model: The Model represents the data and business logic of the application. It encapsulates
the application's data and behaviour. This component is responsible for managing the data
and the rules for manipulating that data. It communicates with the database or any other
data source to retrieve or update data.
2. View: The View represents the presentation layer of the application. It is responsible for
rendering the user interface and displaying data to the user. Views receive data from the
Model and present it to the user in a suitable format, such as HTML for web applications.
3. Controller: The Controller acts as an intermediary between the Model and the View. It
receives user input, processes it (often by interacting with the Model), and decides which
View to render in response. The Controller handles the flow of the application, routing
requests to the appropriate components.
Here's a diagram illustrating the flow of data and interactions in the MVC architecture:
In this diagram:
The user interacts with the application through the View, typically by sending requests (e.g.,
clicking buttons, filling forms).
The Controller receives these user inputs, processes them, and interacts with the Model to
fetch or manipulate data.
The Model represents the data and business logic of the application. It communicates with
the database or any other data source.
Once the Model has processed the data, the Controller selects an appropriate View and
passes the processed data to it.
The View then renders the data received from the Controller and presents it to the user in a
suitable format (e.g., HTML for web applications).
This separation of concerns in MVC architecture makes the code base easier to maintain, test, and
scale, as changes in one component do not necessarily require changes in the others.
4. Web Development Support: Java EE offers a comprehensive set of APIs and tools for
building web applications, including Servlets, JSP, JSF, Expression Language (EL), Java
Persistence API (JPA) for database access, and Java API for WebSocket (WebSocket API) for
real-time communication. These technologies enable the development of dynamic,
interactive, and scalable web applications.
5. Security: Security is a critical aspect of enterprise applications, and Java EE provides robust
mechanisms for securing applications and data. It includes features such as authentication,
authorization, data integrity, and confidentiality. Java EE security features can be configured
and customized to meet specific application requirements, ensuring that sensitive
information is protected from unauthorized access and malicious attacks.
6. Transaction Management: Java EE provides support for managing transactions within
enterprise applications. It offers a high-level API (Java Transaction API - JTA) for coordinating
distributed transactions across multiple resources, such as databases, message queues, and
other enterprise systems. Java EE containers handle transaction management transparently,
ensuring data consistency and reliability in transactional operations.
7. Concurrency and Scalability: Java EE applications can efficiently handle concurrent requests
and scale to meet growing demands. Java EE containers manage concurrency and scalability
by providing features such as thread pooling, connection pooling, load balancing, and
clustering. These features enable applications to handle large numbers of users and
maintain performance under heavy loads.
8. Integration with Existing Systems: Java EE supports integration with existing enterprise
systems and legacy applications through standards-based APIs and protocols. It provides
connectors for integrating with enterprise information systems (EIS) such as databases,
messaging systems, and legacy applications. Java EE also supports interoperability with other
technologies and platforms through standard protocols such as HTTP, SOAP, and REST.
3. Give the characteristics of the HTTP protocol and explain the GET,
HEAD and PUT methods of the HTTP protocol.
HTTP (Hypertext Transfer Protocol) is the underlying protocol used for communication on the World
Wide Web. It is a stateless, application-layer protocol that operates over TCP/IP, facilitating the
transfer of hypertext documents, such as HTML files, between clients (e.g., web browsers) and
servers. Here are some characteristics of the HTTP protocol:
1. Stateless: HTTP is stateless, meaning each request from a client to a server is independent
and unrelated to previous requests. The server does not maintain any information about
past requests, which simplifies implementation and improves scalability.
2. Text-based Protocol: HTTP messages are text-based, consisting of headers and an optional
message body. This makes HTTP human-readable and easy to debug using tools like web
browsers' developer tools or network monitoring software.
5. Cacheability: HTTP supports caching of responses, allowing clients to store and reuse
previously retrieved resources. This reduces server load and improves performance by
minimizing network traffic.
Now, let's explain the GET, HEAD, and PUT methods of the HTTP protocol:
1. GET Method:
GET requests are typically used to retrieve data, such as web pages, images, or other
resources, identified by a URL.
2. HEAD Method:
The HEAD method is similar to GET but requests only the headers of a resource,
without the response body.
It is often used to retrieve metadata about a resource, such as its content type, last
modification date, or content length, without actually fetching the resource's
content.
HEAD requests are useful for checking resource availability, determining caching
information, or verifying resource integrity.
The response to a HEAD request contains the same headers as a corresponding GET
request but without the response body.
3. PUT Method:
The PUT method is used to upload or replace a resource at the specified URI.
It is an idempotent operation, meaning repeated PUT requests with the same data
should have the same result.
PUT requests are often used to update or create resources on the server.
The request body of a PUT request contains the data to be stored or updated at the
specified URI.
PUT requests are typically used in RESTful APIs for creating or updating resources.
This driver uses the JDBC API to interact with an ODBC (Open Database Connectivity)
driver, typically provided by the database vendor.
It translates JDBC calls into ODBC calls, allowing Java applications to connect to any
database for which an ODBC driver is available.
Advantages:
Disadvantages:
This driver uses a database-specific native client library to interact directly with the
database.
It communicates with the database using the vendor's proprietary network protocol.
Advantages:
Disadvantages:
Advantages:
Disadvantages:
Also known as the JDBC Net-Protocol driver, this driver communicates directly with
the database server using a database-specific network protocol (e.g., TCP/IP).
It does not require any native database libraries or middleware servers, making it
highly portable and efficient.
Advantages:
Disadvantages:
Portability: Thin drivers are more portable and platform-independent, while native and
middleware drivers may be platform-specific.
Compatibility: Ensure that the selected driver is compatible with the target database and
environment.
Both CallableStatement and PreparedStatement are interfaces provided by the JDBC API to execute
SQL statements against a database. They offer advantages over regular Statement objects in terms
of performance, security, and code reusability.
PreparedStatement:
PreparedStatement is ideal for executing SQL queries that need to be executed multiple
times with different parameter values.
Here's an example of using PreparedStatement to insert data into a table:
import java.sql.*;
String sql = "INSERT INTO users (name, email) VALUES (?, ?)";
// Set parameters
statement.setString(2, "[email protected]");
if (rowsInserted > 0) {
} catch (SQLException e) {
e.printStackTrace();
CallableStatement:
It allows for calling database stored procedures with input parameters and retrieving output
parameters or result sets.
import java.sql.*;
public class CallableStatementExample {
statement.setInt(1, 101);
statement.registerOutParameter(2, Types.VARCHAR);
statement.execute();
} catch (SQLException e) {
e.printStackTrace();
import java.sql.*;
statement.setInt(1, departmentId);
while (resultSet.next()) {
System.out.println();
} catch (SQLException e) {
e.printStackTrace();
2. We define our SQL query with a placeholder (?) for the department ID.
deleteRecord(connection, "1234567890");
printCustomersWithBalanceGreaterThan(connection, 20000);
} catch (SQLException e) {
e.printStackTrace();
String sql = "INSERT INTO Bank (AccountNo, CustomerName, Balance, Phone, Address) VALUES
(?, ?, ?, ?, ?)";
statement.setString(1, accountNo);
statement.setString(2, customerName);
statement.setDouble(3, balance);
statement.setString(4, phone);
statement.setString(5, address);
statement.setString(1, newAddress);
statement.setString(2, accountNo);
statement.setString(1, accountNo);
// Method to print values of all customers whose balance is greater than the specified amount
statement.setDouble(1, amount);
while (resultSet.next()) {
", Balance: " + balance + ", Phone: " + phone + ", Address: " + address);
Here's an example code to insert three records into the student table using PreparedStatement:
import java.sql.*;
} catch (SQLException e) {
e.printStackTrace();
static void insertRecord(Connection connection, String name, int rollNo, String branch) throws
SQLException {
String sql = "INSERT INTO student (Name, RollNo, Branch) VALUES (?, ?, ?)";
statement.setString(1, name);
statement.setInt(2, rollNo);
statement.setString(3, branch);
9. What are the differences between Java Bean and basic java class?
Explain Java Bean Architecture.
Java Bean and basic Java class are both Java programming constructs but serve different purposes
and follow different conventions. Here are the key differences between them:
1. Purpose:
Basic Java Class: A basic Java class is a fundamental building block of Java programs.
It encapsulates data and behavior related to a specific concept or entity within an
application. Basic Java classes are not specifically designed to be manipulated
visually in builder tools like Java Beans.
2. Conventions:
Java Bean: Java Beans follow specific conventions defined by the Java Bean
specification. These conventions include providing a public default constructor,
exposing properties using getter and setter methods, supporting serialization, and
following naming conventions for methods and properties (e.g., getXxx, setXxx).
Basic Java Class: Basic Java classes do not necessarily follow the conventions defined
by the Java Bean specification. They may or may not have a default constructor,
getter/setter methods, or serialization support, depending on the requirements of
the application.
3. Usage:
Java Bean: Java Beans are typically used in GUI development, where visual
components need to be easily integrated, configured, and manipulated in builder
tools. They provide a standardized way to represent and manage GUI components.
Basic Java Class: Basic Java classes are used to model various entities, concepts, or
functionalities within an application. They may represent domain objects, utility
classes, data access objects, or other types of components.
4. Integration:
Java Bean: Java Beans are designed for easy integration into visual builder tools,
IDEs (Integrated Development Environments), and application frameworks. They
often rely on introspection and reflection mechanisms to enable dynamic
manipulation and configuration.
Basic Java Class: Basic Java classes are integrated into Java applications using
traditional programming techniques. They are instantiated, configured, and used
directly within the application code.
The Java Bean architecture defines a set of conventions and guidelines for creating reusable
software components in Java. Key aspects of Java Bean architecture include:
Properties: Java Beans encapsulate data using properties, which are accessed through getter
and setter methods. Properties provide a standardized way to access and manipulate the
state of Java Bean objects.
Events: Java Beans can generate and listen to events, allowing them to communicate with
other components in an application. Events follow the observer design pattern, where
listeners register interest in specific events and are notified when those events occur.
Customization: Java Beans support customization through properties, events, and methods.
Builders and IDEs can interact with Java Beans to configure their properties, handle events,
and invoke methods dynamically.
10. What is JDBC driver? What is its role? List the types of drivers and
explain working of type-4 driver. Give the different ways to create the
JDBC connection with example.
JDBC (Java Database Connectivity) driver is a software component that enables Java applications to
interact with databases using the JDBC API. The JDBC driver acts as a bridge between the Java
application and the database server, allowing the application to send SQL queries and commands to
the database and retrieve results.
1. Establishing Connection: The JDBC driver establishes a connection to the database server
using the appropriate protocol (e.g., TCP/IP, HTTP) and driver-specific mechanisms.
2. Executing Queries: The JDBC driver executes SQL queries and commands sent by the Java
application against the database server. It translates JDBC calls into database-specific
commands understandable by the database server.
3. Retrieving Results: The JDBC driver retrieves the results of SQL queries and commands from
the database server and provides them back to the Java application in a format usable by
Java code (e.g., ResultSet).
1. Type 1: JDBC-ODBC Bridge Driver: This driver uses an ODBC (Open Database Connectivity)
driver provided by the operating system to connect to the database. It acts as a bridge
between JDBC and ODBC APIs.
2. Type 2: Native-API Driver: This driver communicates directly with the database server using
a database-specific native client library. It interacts with the database using the vendor's
proprietary network protocol.
3. Type 3: Network Protocol Driver (Middleware Driver): This driver communicates with a
middleware server, which acts as an intermediary between the Java application and the
database server. The middleware server translates JDBC calls into a database-independent
protocol understood by the database server.
4. Type 4: Thin (Direct) Driver: This driver communicates directly with the database server
using a database-specific network protocol (e.g., TCP/IP). It does not require any
intermediate translation layers or additional client libraries.
The Type 4 driver is implemented entirely in Java and does not require any native code or
additional client libraries.
When a Java application requests a database connection using the Type 4 driver, the driver
establishes a direct connection to the database server over the network.
Once the connection is established, the Type 4 driver sends SQL queries and commands to
the database server and retrieves the results directly.
Since there are no intermediate translation layers or additional dependencies, the Type 4
driver offers improved performance and portability compared to other driver types.
1. Using DriverManager:
Here's a procedure to insert a row into the table student (roll_no, name, percentage) and call it
using a CallableStatement in a JDBC application:
Assuming we have a stored procedure named insert_student in the database that takes three input
parameters: roll_no, name, and percentage, and inserts a new row into the student table.
DELIMITER //
CREATE PROCEDURE insert_student(
IN p_roll_no INT,
IN p_name VARCHAR(255),
IN p_percentage FLOAT
BEGIN
INSERT INTO student (roll_no, name, percentage) VALUES (p_roll_no, p_name, p_percentage);
END //
DELIMITER ;
import java.sql.*;
} catch (SQLException e) {
e.printStackTrace();
statement.setInt(1, rollNo);
statement.setString(2, name);
statement.setDouble(3, percentage);
statement.execute();
12. Give the hibernate architecture and discuss each part in brief.
Hibernate is an object-relational mapping (ORM) framework for the Java programming language. It
provides a way to map Java objects to relational database tables and vice versa, enabling developers
to work with databases using an object-oriented approach. The Hibernate architecture consists of
several components, each playing a specific role in the framework. Here's an overview of the
Hibernate architecture and its components:
1. Hibernate Configuration:
2. SessionFactory:
3. Session:
A Session is a lightweight and short-lived object representing a single unit of work
with the database.
It serves as a bridge between the Java application and the underlying database.
The Session interface provides methods for performing database CRUD operations
(Create, Read, Update, Delete), querying data, and managing transactions.
4. Transaction:
5. Entities (POJOs):
Entities, also known as Plain Old Java Objects (POJOs), are Java classes that
represent persistent data stored in the database.
Hibernate uses reflection and metadata to map entities to database tables, columns,
and relationships.
6. Mappings:
Mappings define the relationship between Java objects and database tables.
They specify how attributes of Java classes are mapped to columns in database
tables.
Mappings can be defined using XML mapping files or annotations directly within Java
classes.
7. Queries:
Hibernate provides various ways to query data from the database, including HQL
(Hibernate Query Language), Criteria API, and native SQL queries.
Criteria API provides a type-safe and object-oriented way to build dynamic queries
using criteria objects.
Native SQL queries allow executing native SQL queries directly against the database.
8. Caching:
Hibernate supports caching mechanisms to improve application performance by
reducing the number of database queries.
In the context of Hibernate, Object-Relational Mapping involves the following key concepts:
1. Entities:
They are typically modeled as Java classes, also known as Plain Old Java Objects
(POJOs).
Each entity class maps to a specific database table, with each attribute of the class
mapping to a column in the table.
2. Mappings:
Mappings define the relationship between entity classes and database tables.
They specify how attributes of Java classes are mapped to columns in database
tables, and how relationships between entities are represented in the database
schema.
Mappings can be defined using XML mapping files or annotations directly within Java
classes (using Hibernate Annotations).
3. Session:
The Session in Hibernate represents a single unit of work with the database.
It serves as a gateway between the application code and the underlying database,
allowing CRUD (Create, Read, Update, Delete) operations to be performed on
entities.
4. Transaction:
Transactions ensure data consistency and integrity by grouping multiple database
operations into a single atomic unit of work.
5. Query Language:
Hibernate provides its own query language called Hibernate Query Language (HQL),
which is similar to SQL but operates on entity objects rather than database tables.
Additionally, Hibernate supports Criteria API for building dynamic queries using
type-safe criteria objects, and native SQL queries for executing raw SQL statements
against the database.
6. Caching:
The difference between PreparedStatement and Statement in JDBC lies in their purpose, usage, and
benefits:
1. Purpose:
Statement: The Statement interface in JDBC is used to execute static SQL queries
without any parameters. It is typically used for executing SQL queries where the
values are known at compile-time and do not need to be parameterized.
2. Parameterization:
3. Compilation:
Statement: Statements execute SQL queries directly against the database each time
they are executed. They do not undergo any precompilation process.
4. Performance:
Statement: Statements may suffer from performance overhead when executing SQL
queries repeatedly, especially if the same query is executed with different
parameter values, as each execution requires parsing and optimization by the
database server.
2. Create a servlet to handle form submission, calculate percentage, and display the result.
<!DOCTYPE html>
<html>
<head>
<title>Calculate Percentage</title>
</head>
<body>
</form>
</body>
</html>
2. Servlet (CalculatePercentageServlet.java):
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CalculatePercentageServlet extends HttpServlet {
// Calculate percentage
// Display percentage
response.setContentType("text/html");
response.getWriter().println("<html><body>");
response.getWriter().println("</body></html>");
The life cycle of a JSP (JavaServer Pages) consists of several stages, each serving a specific purpose in
the processing of a JSP page. Here are the various stages of the JSP life cycle along with their
functions:
1. Translation:
In the translation phase, the JSP container translates the JSP file into a servlet class.
The container parses the JSP file, generates Java code for the servlet, and compiles it
into a servlet class.
This phase happens only once during the initial deployment or when the JSP file is
modified.
2. Compilation:
During compilation, the generated servlet class is compiled into bytecode by the
Java compiler.
The resulting bytecode is then loaded by the class loader and instantiated as a
servlet object.
3. Initialization:
In the initialization phase, the servlet's init() method is called by the container.
This phase allows the servlet to perform any necessary one-time initialization tasks,
such as loading configuration settings, establishing database connections, or
initializing resources.
4. Request Processing:
The request processing phase begins when a client sends an HTTP request to access
the JSP page.
The container creates a servlet instance and invokes its service() method, passing
the request and response objects as parameters.
The service() method generates dynamic content based on the request parameters,
session attributes, and application logic.
If the JSP file has been modified since the last translation phase, the container
repeats the translation and compilation phases to update the servlet class.
This ensures that any changes made to the JSP file are reflected in the generated
servlet code.
6. Request Handling:
During request handling, the servlet processes the client's request by executing the
generated Java code.
The servlet retrieves data from the request object, performs any necessary business
logic or data processing, and generates the response content.
7. Destroy:
The destroy() method of the servlet is called by the container when the servlet is
being removed from service or the web application is being shut down.
This phase allows the servlet to perform cleanup tasks, release resources, and
gracefully terminate any active connections or threads.
4. List and explain various stages of Servlet Life cycle. Explain role of
web container.
The life cycle of a servlet consists of several stages, each serving a specific purpose in the processing
of client requests and responses. Here are the various stages of the servlet life cycle along with their
explanations:
1. Loading:
The loading stage occurs when the servlet container loads the servlet class into
memory.
This typically happens when the servlet container starts up, or when the servlet is
accessed for the first time.
During loading, the servlet container instantiates the servlet class and initializes it by
calling its init() method.
2. Initialization:
During initialization, the servlet's init() method is called by the servlet container.
This phase allows the servlet to perform any necessary one-time initialization tasks,
such as loading configuration settings, establishing database connections, or
initializing resources.
The init() method is called only once in the servlet's lifecycle, typically during startup
or when the servlet is first accessed.
3. Request Handling:
The request handling stage begins when the servlet container receives an HTTP
request for the servlet.
The servlet container creates a new thread or reuses an existing thread from a
thread pool to handle the request.
The container passes the request and response objects to the servlet's service()
method, which is responsible for processing the request and generating the
response.
The service() method determines the HTTP request method (e.g., GET, POST, PUT,
DELETE) and delegates the request to the appropriate doXXX() method (e.g.,
doGet(), doPost(), doPut(), doDelete()).
4. Response Generation:
During the request handling stage, the servlet generates dynamic content based on
the request parameters, session attributes, and application logic.
The servlet constructs the response by writing data to the response object's output
stream or using other response-related methods.
The generated response may include HTML content, XML data, JSON objects, or
other types of data depending on the application's requirements.
5. Destroy:
The destroy stage occurs when the servlet container removes the servlet from
service or shuts down the web application.
The servlet's destroy() method is called by the servlet container to perform any
necessary cleanup tasks, release resources, and gracefully terminate the servlet.
The destroy() method allows the servlet to close database connections, release file
handles, or perform other cleanup operations before the servlet instance is garbage-
collected.
The role of the web container (servlet container) is to manage the execution and lifecycle of servlets
within a web application. The web container provides a runtime environment for servlets to handle
HTTP requests and responses, ensuring that servlets are loaded, initialized, and executed properly.
Here are some key responsibilities of the web container:
Loading and Initialization: The web container loads servlet classes into memory, instantiates
servlet objects, and initializes them by calling their init() method.
Request Handling: The web container receives HTTP requests from clients, determines
which servlet should handle each request based on the URL mapping configured in the
deployment descriptor (web.xml), and dispatches the request to the appropriate servlet.
Thread Management: The web container manages a pool of threads to handle concurrent
requests from multiple clients. It assigns a thread to each incoming request, ensuring that
servlets are executed in a thread-safe manner.
Request and Response Processing: The web container provides request and response
objects to servlets, allowing them to access request parameters, session attributes, and
other HTTP-related information. It also manages the lifecycle of these objects and ensures
that responses are sent back to clients in a timely manner.
Lifecycle Management: The web container monitors the lifecycle of servlets, including
loading, initialization, request handling, and destruction. It calls the appropriate lifecycle
methods (e.g., init(), service(), destroy()) at the appropriate times to ensure that servlets are
properly managed and resources are released when no longer needed.
Security: The web container enforces security constraints specified in the deployment
descriptor, such as authentication, authorization, and data encryption. It protects sensitive
resources and prevents unauthorized access to web applications.
Context Management: The web container maintains a separate servlet context for each web
application deployed on the server. It manages context initialization parameters, shared
resources, and application-wide settings specific to each web application.
HttpServletRequest:
The HttpServletRequest interface provides methods for accessing the details of an HTTP request sent
by the client to the server. Some of the common methods provided by HttpServletRequest include:
3. getMethod(): Retrieves the HTTP method (GET, POST, PUT, DELETE, etc.) used by the client
for the request.
4. getSession(): Retrieves the HttpSession object associated with the request. Sessions allow
maintaining stateful information across multiple requests from the same client.
6. getHeader(String name): Retrieves the value of a request header specified by its name, such
as "User-Agent", "Host", or "Accept-Language".
7. getCookies(): Retrieves an array of Cookie objects representing the cookies sent by the client
with the request.
8. getInputStream(): Retrieves the input stream containing the request body for reading raw
data sent by the client, such as form data or file uploads.
HttpServletResponse:
The HttpServletResponse interface provides methods for constructing and sending an HTTP response
back to the client. Some of the common methods provided by HttpServletResponse include:
1. setContentType(String type): Sets the MIME type of the response content, such as
"text/html", "application/json", or "image/jpeg".
2. setStatus(int sc): Sets the status code of the response, such as 200 for OK, 404 for Not
Found, or 500 for Internal Server Error.
4. setHeader(String name, String value): Sets a response header with the specified name and
value.
5. getWriter(): Retrieves a PrintWriter object for writing character-based response data, such
as HTML content or JSON strings.
6. sendError(int sc, String msg): Sends an error response with the specified status code and
message to the client.
7. addCookie(Cookie cookie): Adds a Cookie object to the response, which will be sent to the
client and stored on the client's machine.
These request and response objects play a crucial role in servlet programming, allowing developers
to interact with client requests, process data, and construct appropriate responses dynamically.
They provide a rich set of methods for handling various aspects of the HTTP protocol, such as
parameters, headers, cookies, sessions, and content types, making it possible to build powerful and
interactive web applications.
Servlet initialization and destruction events occur when the servlet container loads
and unloads servlet instances.
The contextInitialized() method is called by the servlet container when the web
application is initialized, allowing initialization tasks to be performed.
The contextDestroyed() method is called by the servlet container when the web
application is about to be shut down, allowing cleanup tasks to be performed.
Session lifecycle events occur when HTTP sessions are created, invalidated, or timed
out.
Request lifecycle events occur during the processing of HTTP requests by servlets.
Filters are configured in the deployment descriptor (web.xml) and can be applied to
specific URLs or servlet mappings.
Filters can intercept requests before they reach servlets (doFilter() method invoked
before service() method) and responses before they are sent back to clients.
4. Attribute Changes:
Servlet contexts, sessions, and request objects can store attributes that represent
application, session, and request scope data.
Developers can implement listeners (javax.servlet.ServletContextAttributeListener,
javax.servlet.http.HttpSessionAttributeListener,
javax.servlet.ServletRequestAttributeListener) to be notified when attributes are
added, removed, or replaced.
5. Other Events:
Servlet containers may provide additional event listeners for specific purposes, such
as monitoring servlet lifecycle events, tracking session activity, or handling
asynchronous processing.
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/SessionDemoServlet")
if (visitCount == null) {
visitCount = 1;
} else {
visitCount++;
session.setAttribute("visitCount", visitCount);
response.setContentType("text/html");
out.println("<html>");
out.println("<head><title>Session Demo</title></head>");
out.println("<body>");
out.println("<h1>Session Demo</h1>");
out.println("</body>");
out.println("</html>");
out.close();
In servlet programming, a filter is a Java class that intercepts and processes requests and responses
between a client and a servlet, or between a servlet and a web container. Filters provide a way to
perform preprocessing and postprocessing tasks on requests and responses before they reach their
intended destination. Filters are typically used to perform tasks such as authentication, logging, data
compression, encryption, and content transformation.
1. Filter Interface:
A filter class must implement this interface and override the doFilter() method,
which is called by the servlet container to process requests and responses.
2. Filter Configuration:
The web.xml file specifies the filter class, filter name, URL patterns, and initialization
parameters for each filter.
3. Filter Chain:
When a request is received by the servlet container, it passes the request and
response objects through a chain of filters before reaching the servlet or resource
being requested.
Each filter in the chain can perform preprocessing tasks on the request and
postprocessing tasks on the response.
Filters can also modify the request or response objects and control the flow of the
request by deciding whether to forward the request to the next filter or servlet in
the chain.
4. Filter Lifecycle:
Filters have their own lifecycle, which includes initialization, request processing, and
destruction phases.
The servlet container initializes filters when the web application is started and
destroys them when the application is shut down.
The init() method of a filter is called by the container during initialization, allowing
the filter to perform any necessary setup tasks.
The destroy() method of a filter is called by the container when the filter is being
removed from service, allowing cleanup tasks to be performed.
Filters can be chained together in a specific order to process requests and responses
sequentially.
The order of filters in the chain is determined by their mapping in the web.xml file
or by using annotations (@WebFilter) in servlet 3.0 and later versions.
Filters can pass control to the next filter in the chain by calling the doFilter() method
of the FilterChain object passed as a parameter to the doFilter() method.
In servlet programming, the ServletConfig and ServletContext objects are important components
provided by the servlet container to configure and manage servlets within a web application. Let's
understand the use of each object with examples:
ServletConfig:
These parameters are configured in the deployment descriptor (web.xml) or via annotations
(@WebServlet) and are specific to each servlet.
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.*;
@WebServlet("/ServletConfigDemo")
super.init(config);
this.config = config;
out.println("<html><body>");
out.println("</body></html>");
out.close();
ServletContext:
The ServletContext object represents the servlet container and provides access to
application-wide resources and configuration settings.
It is shared across all servlets and JSP pages within a web application.
Servlet context parameters can be configured in the web.xml file using <context-param>
tags.
Servlet context attributes can be set and retrieved using the setAttribute() and
getAttribute() methods.
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.*;
@WebServlet("/ServletContextDemo")
context.setAttribute("version", "1.0");
response.setContentType("text/html");
out.println("<html><body>");
out.println("</body></html>");
out.close();
In these examples:
ServletConfigDemo servlet retrieves initialization parameters (driver and url) using the
ServletConfig object.
These objects provide mechanisms for servlets to obtain configuration information and share
resources across the entire web application, enhancing modularity, reusability, and configurability.
1. Cookies:
Cookies are small pieces of data stored on the client's machine by the web server.
They are sent back and forth between the client and server with each HTTP request and
response.
Servlets can use cookies to store session identifiers or other session-related data.
Example:
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.*;
@WebServlet("/CookieSessionDemo")
if (cookies != null) {
if (cookie.getName().equals("sessionId")) {
sessionId = cookie.getValue();
break;
if (sessionId == null) {
sessionId = generateSessionId();
response.addCookie(cookie);
if (visitCount == null) {
visitCount = 1;
} else {
visitCount++;
session.setAttribute("visitCount", visitCount);
response.setContentType("text/html");
out.println("<html><body>");
out.println("</body></html>");
out.close();
return UUID.randomUUID().toString();
Servlets can append session IDs or other session-related data to hyperlinks and form actions.
Example:
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.*;
@WebServlet("/UrlRewritingSessionDemo")
if (visitCount == null) {
visitCount = 1;
} else {
visitCount++;
session.setAttribute("visitCount", visitCount);
response.setContentType("text/html");
out.println("<html><body>");
out.println("</body></html>");
out.close();
Hidden form fields can be used to store session information within HTML forms.
Servlets can include hidden input fields in HTML forms to carry session identifiers or other
session-related data.
Example:
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.*;
@WebServlet("/HiddenFormFieldSessionDemo")
if (visitCount == null) {
visitCount = 1;
} else {
visitCount++;
session.setAttribute("visitCount", visitCount);
response.setContentType("text/html");
out.println("<html><body>");
out.println("</form>");
out.println("</body></html>");
out.close();
doGet(request, response);
In JSP (JavaServer Pages), the session object is an implicit object provided by the JSP container that
represents an HTTP session between a client and a web server. The session object allows JSP pages
to maintain stateful information across multiple requests from the same client. It provides methods
for storing, retrieving, and managing session attributes, which are key-value pairs containing data
associated with the session.
Here's an example demonstrating the use of the session object in a JSP page:
<html>
<head>
<title>Session Example</title>
</head>
<body>
<%
if (visitCount == null) {
visitCount = 1;
} else {
visitCount++;
session.setAttribute("visitCount", visitCount);
%>
<h1>Session Example</h1>
</body>
</html>
In this example:
1. We retrieve the session object using request.getSession(true), which returns the existing
session associated with the client or creates a new session if one doesn't exist.
4. We set the updated value of the "visitCount" attribute back into the session using
session.setAttribute("visitCount", visitCount).
5. We use scriptlet tags (<% %>), which allow us to embed Java code directly into the JSP page,
to access the session object and display the visit count.
Here's an example of a Servlet registration to handle form submission from a registration.html page
and display the submitted contents:
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/registration")
response.setContentType("text/html");
response.getWriter().println("<html><body>");
response.getWriter().println("<h1>Registration Details</h1>");
response.getWriter().println("</body></html>");
<!DOCTYPE html>
<html>
<head>
<title>User Registration</title>
</head>
<body>
<h1>User Registration</h1>
<label for="email">Email:</label>
</form>
</body>
</html>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>RegistrationServlet</servlet-name>
<servlet-class>RegistrationServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegistrationServlet</servlet-name>
<url-pattern>/registration</url-pattern>
</servlet-mapping>
</web-app>
13. Write a Login Servlet. Take input username and password from html
file login.html and write the web.xml
Here's an example of a Login Servlet that handles user authentication based on a username and
password input from an HTML form (login.html), along with the corresponding web.xml
configuration:
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/login")
response.setContentType("text/html");
if (isAuthenticated) {
response.getWriter().println("<html><body>");
response.getWriter().println("<h1>Login Successful</h1>");
response.getWriter().println("</body></html>");
} else {
response.getWriter().println("<html><body>");
response.getWriter().println("<h1>Login Failed</h1>");
response.getWriter().println("</body></html>");
<!DOCTYPE html>
<html>
<head>
<title>User Login</title>
</head>
<body>
<h1>User Login</h1>
<label for="username">Username:</label>
<label for="password">Password:</label>
</body>
</html>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
<html>
<head>
<title>Student Information</title>
</head>
<body>
<h1>Student Information</h1>
<table border="1">
<tr>
<td><b>Name:</b></td>
</tr>
<tr>
<td><b>Student ID:</b></td>
</tr>
<tr>
<td><b>Department:</b></td>
</tr>
<tr>
<td><b>Year:</b></td>
</tr>
<tr>
<td><b>Email:</b></td>
</tr>
</table>
</body>
</html>
15. Explain JSP Tag library.
A JSP (JavaServer Pages) tag library, often referred to simply as a tag library or custom tag library, is a
collection of reusable components (tags) that encapsulate complex behavior and functionality in JSP
pages. Tag libraries allow developers to extend the capabilities of JSP by providing a higher level of
abstraction, promoting code reuse, and enhancing maintainability.
Here are the key components and concepts related to JSP tag libraries:
1. Custom Tags:
Custom tags are user-defined tags that provide specialized functionality beyond
what standard JSP tags offer.
Custom tags can be defined using the JSP Tag Library Descriptor (TLD) file and
implemented as Java classes.
Custom tags can encapsulate complex logic, HTML generation, database access, or
any other functionality required in a web application.
The Tag Library Descriptor (TLD) file is an XML file that describes the structure and
behavior of a tag library.
The TLD file defines the tag names, attributes, and tag handlers associated with the
custom tags in the library.
It also provides information about tag documentation, tag attributes, and tag
handlers.
3. Tag Handler:
A tag handler is a Java class that implements the behavior of a custom tag.
Tag handlers are responsible for processing the custom tag's attributes, generating
output, and performing any necessary actions during tag execution.
The Tag Library URI (Uniform Resource Identifier) is a unique identifier used to
reference a tag library within JSP pages.
It serves as a namespace for the custom tags defined in the tag library.
The Tag Library URI is specified in the JSP page using the <%@ taglib %> directive.
Here's an example of a simple TLD file defining a custom tag library with a single
custom tag:
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_3_0.xsd"
version="3.0">
<tlib-version>1.0</tlib-version>
<short-name>example</short-name>
<uri>http://example.com/tags</uri>
<tag>
<name>customTag</name>
<tag-class>com.example.CustomTagHandler</tag-class>
<body-content>empty</body-content>
<attribute>
<name>message</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
To use custom tags in a JSP page, you need to include the tag library directive at the
beginning of the page using the <%@ taglib %> directive.
Once imported, you can use custom tags within the JSP page by specifying their tag names
and attributes.
Custom tags can encapsulate complex functionality and provide a cleaner and more
maintainable way to organize and reuse code in JSP pages.
16. Explain the action tags used to access the JavaBeans from a JSP page
with example.
In JSP (JavaServer Pages), action tags are used to perform various tasks within a JSP page, including
accessing JavaBeans (POJOs representing data) and invoking their methods. The key action tags used
for accessing JavaBeans from a JSP page are <jsp:useBean>, <jsp:setProperty>, and
<jsp:getProperty>. Let's discuss each of these action tags with examples:
1. <jsp:useBean>:
The <jsp:useBean> action tag is used to instantiate or locate a JavaBean in a JSP page.
Syntax:
jspCopy code
Attributes:
id: Name used to refer to the JavaBean within the JSP page.
scope: Optional attribute specifying the scope (page, request, session, or application) in
which the JavaBean should be stored.
Example:
jspCopy code
2. <jsp:setProperty>:
Syntax:
jspCopy code
Attributes:
Example:
jspCopy code
3. <jsp:getProperty>:
The <jsp:getProperty> action tag is used to retrieve property values from a JavaBean and display
them in the JSP page.
Syntax:
jspCopy code
Attributes:
Example:
jspCopy code
jspCopy code
<html>
<head>
<title>JavaBean Example</title>
</head>
<body>
<h1>User Information</h1>
</body>
</html>
In this example:
We instantiate a User JavaBean using <jsp:useBean> and set its properties (firstName and
lastName) using <jsp:setProperty>.
We retrieve and display the property values using scriptlet tags (<%= %>) and
<jsp:getProperty>.
<c:forEach>: Iterates over a collection or array, executing the body of the tag for
each element.
<c:forTokens>: Iterates over a delimited string, splitting it into tokens and executing
the body of the tag for each token.
2. Conditional Tags:
<c:if>: Evaluates a boolean condition and executes the body of the tag if the
condition is true.
<c:set>: Sets the value of a scoped variable (page, request, session, or application).
<c:catch>: Catches any Throwable thrown during the execution of its body and
optionally exposes it as a scoped variable.
6. Formatting Tags:
7. Localization Tags:
<fmt:setLocale>: Sets the locale for formatting and parsing dates, numbers, and
messages.
<c:out>: Escapes HTML and XML characters in the output, preventing XSS (Cross-Site
Scripting) attacks.
9. Miscellaneous Tags:
<c:catch>: Catches exceptions thrown during tag execution.
<c:otherwise>: Used within a <c:choose> tag to define the default condition block.
Attributes:
id: Specifies the name by which the JavaBean will be referred to within the JSP page.
class: Specifies the fully qualified class name of the JavaBean to be instantiated.
scope: Optional attribute specifying the scope (page, request, session, or application) in
which the JavaBean should be stored.
Example:
Suppose we have a simple JavaBean named User that represents user information:
package com.example;
return username;
this.username = username;
this.email = email;
1. request: Represents the HTTP request made by the client to the server.
2. response: Represents the HTTP response sent by the server to the client.
3. out: Represents the output stream for sending content to the client.
4. session: Represents the HTTP session associated with the client, allowing data to be
maintained across multiple requests.
8. pageContext: Represents the PageContext object, providing access to various objects and
attributes related to the JSP page.
9. exception: Represents the exception thrown during the execution of the JSP page.
1. request:
The request implicit object represents the HTTP request made by the client to the server. It provides
access to information sent by the client, such as form parameters, query string parameters, headers,
and cookies. Developers commonly use this object to retrieve user input and interact with the
client's request.
Example:
jspCopy code
2. session:
The session implicit object represents the HTTP session associated with the client. It allows data to
be maintained across multiple requests from the same client. This object is commonly used to store
user-specific data or state information throughout a user's interaction with the application.
Example:
<%
session.setAttribute("username", username);
%>
In this example, we store the user's name in the session using the setAttribute() method of the
session object. This allows us to access and retrieve the user's name across multiple requests during
the same session.
These are just two examples of JSP implicit objects, but each of the implicit objects provides valuable
functionality and access to different aspects of the JSP environment, enabling developers to build
dynamic and interactive web applications efficiently.
20. Write a servlet which counts the number of digits into an integer
received as parameter.Give the necessary web.xml file to deploy the
servlet.
Here's a servlet code that counts the number of digits in an integer received as a parameter:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
out.println("<html><body>");
out.println("</body></html>");
} else {
To deploy this servlet, you also need to configure the web.xml deployment descriptor file. Here's the
web.xml file:
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>DigitCounterServlet</servlet-name>
<servlet-class>DigitCounterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DigitCounterServlet</servlet-name>
<url-pattern>/countDigits</url-pattern>
</servlet-mapping>
</web-app>
21. List the servlet session level events and show that how servlet
destroy event is handled?
In Java servlets, session-level events allow developers to track and respond to changes in session
state. These events are fired by the servlet container (e.g., Apache Tomcat) at various points during
the lifecycle of a session. The following are the session-level events in servlets:
This event is triggered when a new session is created by the servlet container.
It provides access to the HttpSession object associated with the newly created
session.
It provides access to the HttpSession object associated with the session being
destroyed.
import javax.servlet.*;
import javax.servlet.http.*;
22. Write a JSP page that prints your resume in well formatted form.
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Resume</title>
<style>
body {
margin: 0;
padding: 0;
.container {
max-width: 800px;
margin: 0 auto;
padding: 20px;
background-color: #f9f9f9;
h1, h2, h3 {
color: #333;
margin-bottom: 10px;
p{
margin: 5px 0;
.section {
margin-bottom: 20px;
.section h2 {
padding-bottom: 5px;
margin-bottom: 10px;
.experience {
margin-left: 20px;
.experience p {
margin: 5px 0;
</style>
</head>
<body>
<div class="container">
<h1>John Doe</h1>
<p>Email: [email protected] | Phone: (123) 456-7890 | LinkedIn:
linkedin.com/in/johndoe</p>
<div class="section">
<h2>Summary</h2>
<p>An experienced software engineer with expertise in Java, JavaScript, and SQL. Strong
problem-solving skills and a passion for learning new technologies.</p>
</div>
<div class="section">
<h2>Experience</h2>
<div class="experience">
<ul>
</ul>
</div>
<div class="experience">
<ul>
</ul>
</div>
</div>
<div class="section">
<h2>Education</h2>
</div>
</div>
</body>
</html>
23. What are cookies? Write a servlet that reads and prints all the
previous cookies and add a cookie with your name.
Cookies are small pieces of data stored on the client's machine by the web browser. They are
commonly used to store user-specific information or to track user behavior across multiple requests
and sessions. Cookies are sent from the client to the server with every HTTP request, allowing the
server to access and modify the data stored in the cookie.
Here's a servlet that reads and prints all the previous cookies and adds a new cookie with your
name:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
out.println("<html><body>");
out.println("<h1>Previous Cookies:</h1>");
if (cookies != null) {
for (Cookie cookie : cookies) {
} else {
response.addCookie(myCookie);
out.println("</body></html>");
24. Write a servlet which accept two numbers using POST methods and
display the maximum of them.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
out.println("<html><body>");
out.println("<h1>Maximum Number</h1>");
out.println("</body></html>");