Q. Explain the architecture of JDBC in brief.
JDBC (Java Database Connectivity) is a standard API that enables Java applications to interact with relational databases. Its architecture consists of two main layers: the JDBC API and the JDBC Driver Manager/Drivers. The JDBC API provides interfaces like Connection, Statement, PreparedStatement, and ResultSet for executing SQL queries. Underneath, JDBC drivers translate Java calls into database-specific calls. There are four types of JDBC drivers:
The application interacts only with the JDBC API,
while the DriverManager selects a suitable driver to communicate with the
database. This layered architecture allows Java applications to work with
different databases without changing source code.
Q. What is a PreparedStatement?
How is it different from Statement?
A PreparedStatement is a precompiled SQL
statement in JDBC that allows parameters to be set dynamically using
placeholders (?). It improves performance
because the SQL query is compiled only once and reused for multiple executions.
PreparedStatements also prevent SQL injection by treating parameters as data,
not executable code.
A Statement, however, executes static SQL
queries and compiles the SQL each time it is executed, making it slower for
repeated operations. Statements also embed values directly in the SQL string,
which makes them more vulnerable to SQL injection.
For example, PreparedStatement pst = con.prepareStatement("INSERT INTO users
VALUES(?,?)"); allows
setting parameters using pst.setString() safely and efficiently.
Q. List any two advantages of
using transactions in JDBC.
Transactions in JDBC ensure that a group of SQL
operations are executed as a single unit of work. Two major advantages are:
- Data
Integrity:
Transactions guarantee atomicity, consistency, isolation, and durability
(ACID). If any operation fails—such as transferring funds between bank
accounts—rollback() ensures the database remains
consistent.
- Error
Recovery:
Transactions allow safe error handling. If multiple operations depend on
each other, developers can commit only when all succeed. For example,
while booking a ticket, inserting booking details and updating seat
availability must occur together. If one fails, the entire process can be
rolled back.
Thus, transactions ensure safe, reliable, and predictable database operations.
Q. Define RowSet. How is it
different from ResultSet?
A RowSet is a Java interface in JDBC that
represents a tabular data set, like ResultSet, but adds advanced features such
as scrollability, updatability, and the ability to be disconnected from the
database. RowSets are JavaBeans components, meaning they support properties,
event listeners, and serialization.
In contrast, a ResultSet is always connected
to the database and relies on an active Connection. It does
not support event notifications.
RowSets can also function offline, which is useful for mobile or distributed
applications. For example, a CachedRowSet can
retrieve data, disconnect from the database, and later reconnect to update
changes. This flexibility makes RowSets more powerful and portable than
standard ResultSets.
Q. What is the purpose of
Generics in Java?
Generics in Java allow developers to write
type-safe and reusable code by enabling classes, interfaces, and methods to
operate on specified data types. They eliminate the need for casting and reduce
runtime errors by catching type mismatches at compile time. For example, using ArrayList<String> ensures that only String objects
can be stored, preventing accidental insertion of incompatible types.
Generics also support the development of generic
algorithms and data structures. They improve code readability, maintainability,
and performance by eliminating unnecessary casts. In frameworks like
Collections, Generics help achieve strong type checking. Overall, Generics
enhance reusability and reliability while making Java code more robust.
Q. Differentiate between Factory
Design Pattern and Singleton Design Pattern.
The Factory Design Pattern focuses on
creating objects without exposing creation logic to the client. It uses a
common interface and returns different subclass instances based on input. For
example, a ShapeFactory may return a Circle, Square, or Triangle based on the request. It promotes loose coupling
and easy extensibility.
The Singleton Design Pattern, on the other
hand, ensures that only one instance of a class exists throughout the
application. It provides a global point of access using a private constructor
and a static method like getInstance().
While Factory solves object-creation flexibility,
Singleton controls object instantiation to maintain a unique shared resource,
such as configuration managers or loggers.
Q. What is the purpose of
ServletConfig object?
ServletConfig is used
to pass initialization parameters to a servlet during its creation. It allows
configuration information to be stored outside the code, typically in web.xml,
making the application flexible and maintainable. When a servlet is
initialized, the container creates a ServletConfig object
containing name-value pairs defined under the servlet’s configuration.
For example, a servlet may read a database URL or API key from ServletConfig instead of hard-coding it, enhancing security and
portability. Developers can retrieve parameters using getInitParameter(). ServletConfig is
unique per servlet, unlike ServletContext, which
is shared across the entire application.
Q. Explain the difference between
HTTP GET and POST requests.
·
GET requests
send data appended to the URL as query parameters, making them visible in the
address bar. They are used for retrieving data, such as searching products or
fetching details. GET requests have size limitations and are less secure
because data remains exposed. GET requests are idempotent, meaning repeated
calls produce the same result.
·
POST requests
send data inside the request body, making them more secure and suitable for
form submissions, file uploads, or sensitive data. They have no size
restrictions and are not idempotent. For example, submitting a registration
form uses POST because it modifies server-side data.
Thus, GET retrieves data while POST updates or
submits data safely.
Q. What is Expression Language
(EL) in JSP?
Expression Language (EL) is a JSP feature that
simplifies accessing data stored in JavaBeans, request parameters, session
attributes, and application scope. It eliminates the need for lengthy Java code
in JSP pages by allowing expressions like ${user.name} to
retrieve values directly. EL improves readability, reduces scripting, and
promotes cleaner MVC architecture by separating business logic from
presentation. It includes implicit objects such as param, sessionScope, and requestScope and supports operators, functions, and
expressions.
For example, ${sessionScope.cart.total} retrieves the total cart value
from a session object.
EL enables dynamic data binding and easy access to server-side variables
without using Java scriptlets, making JSP pages more maintainable.
Q. What is JDBC DriverManager?
DriverManager is a
JDBC class that manages a list of registered JDBC drivers. It establishes
database connections by selecting the appropriate driver based on the provided
database URL. When the getConnection() method is called, DriverManager
loads the driver, checks compatibility, and handles the connection request.
Developers simply specify the connection URL,
username, and password, and DriverManager manages the rest. It abstracts driver
management, allowing the same Java code to connect to different databases such
as MySQL, Oracle, or PostgreSQL by loading different drivers.
DriverManager also logs connection attempts and
supports driver chaining. Thus, it acts as the central connection manager in
the JDBC architecture.
Q. Define scrollable ResultSet
and its types.
A scrollable ResultSet allows navigation in
both forward and backward directions, unlike the default forward-only
ResultSet. It provides methods like previous(), absolute(), and relative() to move
the cursor to any row. Scrollable ResultSets are useful for UI applications
where users navigate records freely.
There are two major types:
- TYPE_SCROLL_INSENSITIVE: The ResultSet does not
reflect changes made in the database after it is created.
- TYPE_SCROLL_SENSITIVE: Reflects database changes
in real time, making it useful when multiple users modify data
simultaneously.
Scrollable ResultSets enhance flexibility in reading and manipulating data while improving user experience in applications like admin dashboards.
Q. What is autocommit mode in
JDBC?
Autocommit mode is a JDBC feature where each
executed SQL statement is automatically committed to the database. By default,
every INSERT, UPDATE, or DELETE
operation is immediately saved. This mode is suitable for simple operations but
unsuitable for multi-step transactions that must be treated as a single unit of
work.
To manage transactions manually, developers disable
autocommit using conn.setAutoCommit(false) and then explicitly call commit() or rollback(). For
example, during a fund transfer, both debit and credit operations must be
committed together; otherwise, inconsistencies may occur.
Autocommit simplifies development but reduces control, so it’s often disabled
in enterprise applications.
Q. State two differences between
PreparedStatement and CallableStatement.
- Purpose:
- PreparedStatement is used for executing
dynamic or parameterized SQL queries such as INSERT, UPDATE, or SELECT.
- CallableStatement is used for executing
stored procedures and functions in the database.
- Parameter
Handling:
- PreparedStatement supports only IN
parameters using setXXX() methods.
- CallableStatement supports IN, OUT, and
INOUT parameters using registerOutParameter().
For example, calling a stored procedure like {call getSalary(?, ?)} requires CallableStatement to retrieve OUT parameters.
Q. What are the advantages of
Collections over Arrays?
Collections provide many advantages over arrays,
including dynamic size, rich APIs, and better flexibility. Unlike arrays, which
have a fixed size, collections like ArrayList grow or
shrink automatically. Collections support advanced operations such as sorting,
searching, filtering, and iteration using the Collections Framework. They can
store heterogeneous objects (if using Generics properly). Collections provide
various data structures, including lists, sets, queues, and maps, each
optimized for specific use cases.
They also integrate with algorithms like binary search and hashing. For
example, a HashMap allows key-value storage with
constant-time lookup, something arrays cannot easily achieve. Collections
improve code readability, maintainability, and performance in modern Java
applications.
Q. Define a Design Pattern. Give
one real-world use case.
A Design Pattern is a reusable solution to a
common software design problem. It represents best practices refined by
experienced developers and provides a template for solving recurring issues in
software architecture. Design patterns improve code reusability,
maintainability, and flexibility by offering standardized structures and
interactions.
A real-world example is the Observer Pattern, used in event-driven
systems. When the state of an object changes, all registered observers are
automatically notified. This pattern is widely used in GUI frameworks, where
clicking a button triggers multiple listeners, or in real-time systems such as
stock market updates.
Design patterns streamline communication and
development across teams by offering shared vocabulary.
Q. What is the role of
HttpServletRequest object?
HttpServletRequest provides
information about the client’s request in a servlet-based application. It
allows developers to access request parameters, headers, cookies, attributes,
HTTP methods, and session objects. For example, parameters submitted through a
login form can be retrieved using request.getParameter("username").
It also provides methods to determine the request
type (GET/POST), retrieve client metadata such as IP address, and manage
request attributes used for inter-servlet communication. Additionally, it helps
retrieve multipart data, path information, and cookies.
Overall, HttpServletRequest acts as the primary interface
for interacting with client-submitted data and controlling the request
lifecycle in a web application.
Q. Explain URL rewriting.
URL rewriting is a technique used to maintain
session tracking when cookies are disabled on the client side. It works by
appending a session ID to the URL automatically by the server using methods
like response.encodeURL().
For example, a URL may appear as http://example.com/home;jsessionid=12345. This allows the server to
identify the user’s session across requests.
URL rewriting ensures continuity in shopping carts,
user logins, and personalized content. However, it may expose session IDs in
the browser history and logs, so it must be used carefully. URL rewriting is an
essential fallback mechanism for session management in servlet-based
applications.
Q. What is the purpose of JSP
expression tags? Give an example.
JSP expression tags (<%= ... %>) are used to output values directly into the HTML
response. They evaluate and print the result of Java expressions without
needing out.println(). Expression tags are useful for
displaying dynamic content like usernames, dates, or computed values.
For example:<%= new java.util.Date() %>
This prints the current date and time in the
browser.
Expression tags automatically convert the expression result to a string and
insert it into the output stream. They improve readability but should be used
sparingly, as modern JSP prefers EL and JSTL for cleaner separation of logic
and presentation.
Q. Write
any two EL implicit objects and their usage.
- param – Used to access request
parameters. Example: ${param.username} retrieves the value of the “username” parameter
submitted via an HTML form.
- sessionScope – Refers to session
attributes stored for the user. Example: ${sessionScope.user} accesses the logged-in user
object stored in the session.
These implicit objects simplify JSP development by eliminating Java scriptlets and allowing easy access to application data.
Q.
Explain Steps involved in processing SQL statements using JDBC
Processing SQL statements in JDBC follows a
structured sequence that enables Java applications to interact with relational
databases in a standardized way. The first step involves loading the JDBC
driver, traditionally done using Class.forName(), though
modern JDBC uses the Service Provider mechanism for auto-loading. Next, a database
connection is established using DriverManager.getConnection() or a DataSource, which
returns a Connection object. Once the connection is
available, developers create a Statement, PreparedStatement, or
CallableStatement depending on the type of SQL operation. PreparedStatement is preferred for efficiency and security because
it precompiles SQL queries and prevents SQL injection. After preparing the
statement, parameters are optionally set using setter methods like setInt() or setString().
Execution is performed using methods such as executeQuery() for SELECT or executeUpdate() for
INSERT, UPDATE, DELETE. The results of queries are retrieved through a ResultSet,
where cursor-based iteration allows reading row-by-row data. After processing,
all JDBC resources—ResultSet, Statement, and Connection—must be explicitly
closed to avoid leaks. Typically, closing is wrapped in a finally block
or handled using try-with-resources, ensuring safe cleanup. This
structured process ensures reliable and secure database interaction in advanced
Java applications.
Q. Write Java
program to insert student records using PreparedStatement
Using PreparedStatement for
inserting records enhances security and performance in JDBC applications. It
allows precompiled SQL statements and safe parameter binding, preventing SQL
injection. Below is a Java program demonstrating insertion of student records.
Code Example
import java.sql.*;
public class InsertStudent {
public
static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/school";
String user = "root";
String pass = "password";
String sql = "INSERT INTO students(id, name, grade) VALUES (?, ?,
?)";
try
(Connection con = DriverManager.getConnection(url, user, pass);
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setInt(1, 101);
ps.setString(2, "Rahul Sharma");
ps.setString(3, "A");
int rows = ps.executeUpdate();
System.out.println(rows + " record inserted successfully.");
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
Explanation
This program demonstrates building a robust
database insert operation using PreparedStatement. The
database connection is established using DriverManager.getConnection(), providing the JDBC URL and credentials. The SQL
query contains placeholders (?), which enable dynamic parameter
substitution. A PreparedStatement object is created by passing the
SQL query to con.prepareStatement(), allowing the JDBC driver to
precompile the statement. Parameters are set using type-specific setter methods
such as setInt() and setString(), ensuring type safety. The call to executeUpdate() sends the compiled SQL statement to the database
and returns the number of affected rows. Using try-with-resources guarantees
that the Connection and PreparedStatement are closed automatically. If an error
occurs, the catch block handles SQLException, which
may result from constraint violations, incorrect syntax, or connection errors.
This approach is preferred over Statement because
it enhances performance, avoids SQL injection, and simplifies working with
dynamic data in real-world enterprise systems.
Q.
Explain JDBC exceptions and How SQLException is handled?
JDBC operations can lead to several types of
exceptions, primarily represented by SQLException, the root class for
all JDBC-related errors. Common exceptions include SQLSyntaxErrorException,
thrown when the SQL query has incorrect syntax; SQLIntegrityConstraintViolationException,
raised when operations violate constraints like primary keys or foreign keys;
and SQLTimeoutException, which occurs when a database operation exceeds
its allowed execution time. Another common issue is SQLNonTransientConnectionException,
which indicates a lost or invalid connection. SQLException provides detailed diagnostic information through
methods such as getMessage(), getSQLState(), and getErrorCode(). These
offer insights into the vendor-specific cause of failure.
Handling SQLException
typically involves using try-catch blocks around JDBC operations. Developers
often log error details and implement recovery strategies such as retrying
operations or rolling back transactions. When performing multi-step operations,
SQLException must be handled alongside
transaction management to prevent partial updates. Proper handling ensures the
application remains robust, secure, and fault-tolerant, especially in
enterprise environments where database failures can significantly impact system
reliability.
Q. Explain
purpose and usage of DataSource object in connection pooling.
A DataSource object
represents an advanced alternative to the traditional DriverManager for obtaining database connections in enterprise
applications. Its primary purpose is to support connection pooling,
which significantly enhances performance by reusing existing database
connections rather than creating a new connection for each request. Creating a
connection is resource-intensive, so pooling minimizes overhead, reduces
latency, and improves scalability. DataSource
implementations are usually provided by application servers such as Apache
Tomcat, WebLogic, or JBoss, and configurations are defined externally in XML or
server configuration files. Once configured, the Java application retrieves a Connection using JNDI lookup, for example:
Context ctx = new InitialContext();
DataSource ds = (DataSource)
ctx.lookup("jdbc/mydb");
Connection con = ds.getConnection();
The server maintains a managed pool of connections,
and the getConnection() call fetches a ready-to-use
connection from the pool. After use, calling con.close() does not actually close the physical connection;
instead, it returns the connection to the pool. This architecture supports load
balancing, distributed transactions, and improved resource
utilization—essential in scalable enterprise Java applications.
Q.
Explain Generics and how they improve type safety?
Generics in Java allow classes, interfaces, and
methods to operate on parameterized types, enabling type-safe code while
maintaining flexibility. They prevent runtime type-casting errors by shifting
type checking to compile time. For example, declaring a List<String> ensures that only String objects can be stored. Without Generics, a List would accept any type, and retrieving elements
would require explicit casting, risking ClassCastException. Example:
List<Integer> numbers = new
ArrayList<>();
numbers.add(10); // allowed
Generics also support custom generic classes:
class Box<T> {
private T
value;
public
void set(T value) { this.value = value; }
public T
get() { return value; }
}
Here, T acts as
a placeholder, allowing the class to be instantiated as Box<String> or Box<Integer>.
Generics enable reusability and abstraction without compromising type safety.
They also improve performance by avoiding unnecessary casting. Additionally,
bounded type parameters, such as <T extends Number>, restrict acceptable types, enabling numeric operations. Wildcards like
<?> or <? extends T> support flexibility in method parameters. Overall,
Generics provide compile-time safety, cleaner code, and improved
maintainability—essential qualities for modern Java enterprise systems.
Q.
Explain Collection Framework and any two collection classes?
The Java Collection Framework (JCF) is a
comprehensive architecture for storing, retrieving, and manipulating groups of
data efficiently. It provides interfaces such as List, Set, Queue, and Map,
along with implementation classes and algorithms that handle dynamic data
structures. The framework standardizes how collections are managed and provides
powerful utilities like sorting, searching, and iteration.
·
ArrayList : ArrayList is a resizable array
implementation of the List interface. It allows indexed access, maintains
insertion order, and provides fast retrieval due to its underlying dynamic
array structure. When capacity is exceeded, it grows automatically. However,
insertions in the middle and deletions are relatively slower due to element
shifting. It's ideal for applications requiring frequent reads and infrequent
modifications.
·
HashSet: HashSet implements the Set interface and
stores unique elements using hashing. It provides constant-time performance for
add, remove, and contains operations, assuming a good hash function. It does
not maintain any insertion order. HashSet is suitable when the goal is to
prevent duplicates and perform fast membership tests. Both classes enhance
productivity by providing ready-to-use, optimized data structures for
enterprise applications.
Q.
Explain Singleton Design Pattern with UML and example
The Singleton Pattern ensures that a class
has only one instance throughout the application and provides a global point of
access to it. It is often used for shared resources such as configuration
settings, logging, or database connections.
UML Representation
+---------------------------------+
| Singleton |
+---------------------------------+
| - instance: Singleton (static) |
+----------------------------------+
| + getInstance(): Singleton |
| - Singleton() |
+----------------------------------+
Code Example
public class Singleton {
private
static Singleton instance;
private
Singleton() { }
public
static synchronized Singleton getInstance() {
if
(instance == null) {
instance = new Singleton();
}
return instance;
}
}
Explanation
The Singleton pattern restricts the instantiation
of a class by making its constructor private. The static getInstance() method checks whether an instance already exists;
if not, it creates one. Synchronization ensures thread safety in multithreaded
applications. Alternative implementations include eager initialization and
using an enum for simplicity. This pattern ensures controlled access, lazy
initialization, and resource efficiency. It is widely used in advanced Java
frameworks where shared resources must be consistently managed across modules.
Q. How
Factory Design Pattern provides loose coupling
The Factory Design Pattern promotes loose
coupling by delegating object creation to a separate factory class rather than
instantiating objects directly in client code. This decoupling ensures that the
client depends only on abstractions (interfaces or abstract classes) instead of
concrete classes. When business logic requires different implementations, the
client need not modify its code.
For example, consider an interface Shape with implementations like Circle and Rectangle. The ShapeFactory contains a method getShape(String type) that returns the appropriate object. Client code
simply calls:
Shape s =
ShapeFactory.getShape("CIRCLE");
The client does not know or care about how the Circle object is created. If a new shape (e.g., Triangle)
is added, modifications occur only in the factory, not in all client modules.
This separation enhances maintainability, scalability, and unit testing. It
also encourages design principles such as Dependency Inversion and Open/Closed
Principle, making the overall system flexible and extensible.
Q. MVC
architecture for web applications with example
The Model-View-Controller (MVC) architecture
divides a web application into three interconnected components to simplify
development and support separation of concerns. The Model represents
business data and rules, often consisting of POJOs, DAOs, and service classes
that communicate with the database. The View handles user interface
representation, typically implemented using JSP pages, HTML, or front-end frameworks.
The Controller processes user requests, interacts with the Model, and
determines which view should be returned.
For example, in a student management web
application, a user submits a form to fetch student records. The request goes
to a Servlet acting as a Controller. It reads input parameters, calls the Model
layer to retrieve data, and finally forwards the result to a JSP View for
rendering. MVC ensures each layer is independent, enhances reusability, and
supports testability. Frameworks like Spring MVC and Struts use this
architecture extensively.
Q. Complete
life cycle of a servlet
A servlet's life cycle consists of three primary
phases: initialization, request handling, and termination.
When the servlet is first loaded into memory, usually upon the first request or
during server startup (if load-on-startup is configured), the servlet container
creates an instance and calls its init(ServletConfig config) method. This method is used for resource
initialization such as establishing database connections or reading
configuration parameters.
Next is the service phase, where the servlet
handles multiple client requests concurrently. The container invokes the service() method, which then dispatches requests to
appropriate handler methods like doGet() or doPost() based on the HTTP method. This phase forms the
core of request processing—reading parameters, interacting with business logic,
and generating responses.
Finally, when the server shuts down or the
application is undeployed, the container calls the destroy() method. This method releases resources, closes
connections, and performs cleanup to avoid resource leaks. Throughout its
lifecycle, the container manages threading, object reuse, and efficiency,
making servlets a foundational component of Java web application development.
Q. Explain
Init parameters vs Context init parameters
Init parameters are configuration values defined specifically for
a particular servlet. They are declared inside the <servlet> tag in web.xml or using
annotations like @WebInitParam. These parameters remain
constant and are used for servlet-specific settings such as default values or
file paths. They are retrieved using
getServletConfig().getInitParameter("name").
In contrast, Context init parameters are
global to the entire web application and defined inside the <context-param> tag. They represent shared configuration values
like database URLs, application-wide settings, or API keys. They are retrieved
using
getServletContext().getInitParameter("name").
The key difference lies in their scope: servlet
init parameters apply only to a single servlet, whereas context init parameters
are accessible throughout all servlets and JSP pages in the application. Using
them effectively allows centralized configuration management, making the
application more maintainable and flexible.
Q.
Explain HTTP request and response structure
An HTTP request consists of three major
parts: the request line, headers, and message body. The request line includes
the method (GET, POST, etc.), the URL, and the HTTP version, such as:
GET /index.html HTTP/1.1
Headers provide metadata such as Host, User-Agent, Cookie, and Content-Type. The
body contains form data, JSON, or other payload, typically in POST or PUT
requests.
An HTTP response also contains a status line,
headers, and a body. The status line includes the HTTP version, status code
(e.g., 200 OK, 404 Not Found), and reason phrase. Headers such as Content-Type, Set-Cookie, and Cache-Control specify response metadata. The response body
carries HTML content, JSON output, files, or other resources requested by the
client.
Diagram (textual representation)
Request → [Request Line | Headers | Body]
Response → [Status Line | Headers | Body]
Understanding the structure is essential for
servlet developers who frequently read requests and generate dynamic responses.
Q.
Explain Session management techniques in servlets
Session management maintains state across multiple
HTTP requests, as HTTP is stateless by nature. Servlets support several
techniques.
1.
Cookies: Small
text data stored in the client browser. The server sends a Set-Cookie header, and the browser returns it on each
request. They can store session IDs but may be disabled by users.
2.
URL Rewriting: The
session ID is appended to the URL as ;jsessionid=12345. This
technique works even when cookies are disabled but requires modifying all links
dynamically.
3.
Hidden Form Fields: Session data is stored in hidden HTML fields and sent with each form
submission. This works only for form-based navigation.
4.
HttpSession: The most
common mechanism. The container creates a session object identified by a unique
ID. Attributes can be stored and retrieved using setAttribute() and getAttribute(). It
supports timeouts, invalidation, and automatic tracking via cookies or URL
rewriting.
Effective session management ensures
personalization, authentication, and persistent user experience in web
applications.
Q. Write Servlet
program using POST method
Below is a servlet that reads user input using POST
and displays a welcome message.
Code Example
@WebServlet("/welcome")
public class WelcomeServlet extends HttpServlet {
protected
void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String name = req.getParameter("username");
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println("<h2>Welcome, " + name +
"!</h2>");
}
}
Explanation
This servlet handles HTTP POST requests sent from
an HTML form. The annotation @WebServlet("/welcome") maps the servlet to a URL pattern. When a POST
request is submitted, the container invokes the doPost() method. Using getParameter(), the
servlet retrieves user input such as a username. The servlet then sets the
response content type to HTML and obtains a PrintWriter to send
output to the client. It generates a simple welcome message dynamically based
on the input. This example demonstrates request handling, parameter extraction,
and dynamic response generation—fundamental tasks in advanced Java web
applications.
Q.
Explain JSP page life cycle
A JSP page undergoes several phases during its
lifecycle, managed by the servlet container. First, the translation phase
converts the JSP file into a servlet source file. Next, in the compilation
phase, the generated servlet file is compiled into bytecode. The class
loading phase loads the servlet class into memory, followed by the instantiation
phase, where the container creates an instance of the JSP servlet. It then
calls the jspInit() method for initialization, similar to init() in normal servlets.
During request processing, the container invokes
the _jspService() method, which handles all requests to the JSP. This
method is automatically generated and should not be overridden by developers.
After the JSP is no longer needed or the server shuts down, the container calls
jspDestroy() to release resources.
These lifecycle steps make JSP pages powerful yet
efficient for building dynamic content, combining HTML with backend logic.
Q. Explain
Implicit JSP objects with examples
JSP provides nine implicit objects that developers
can use without declaration:
- request – Represents
HttpServletRequest, used to read parameters.
- response – Represents
HttpServletResponse, used to send output.
- out – A JspWriter object used
to write HTML: out.println("Hello");
- session – Represents HttpSession
for managing state.
- application – Represents
ServletContext, storing global data.
- config – Represents ServletConfig
for servlet-specific parameters.
- pageContext – Provides access to all
scopes and utility methods.
- page – Refers to the current JSP
page (like this in Java).
- exception – Available only in error
pages, used to display error details.
These objects simplify coding by giving JSP direct
access to servlet components without manual instantiation.
Q. Explain Scriptless JSP using EL and JSTL to
display products
Below is a scriptless JSP page that displays a list
of products passed as a request attribute.
Code Example
<%@ taglib
uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<body>
<h2>Product List</h2>
<ul>
<c:forEach var="p" items="${products}">
<li>${p.name} - ${p.price}</li>
</c:forEach>
</ul>
</body>
</html>
Explanation
This JSP uses Expression Language (EL) and JSTL to
avoid scriptlets, promoting clean and maintainable code. The <c:forEach> tag iterates over the products attribute, which is typically a List of Product
objects set in the request scope by a servlet:
request.setAttribute("products",
productList);
The EL expression ${p.name} retrieves property values through getter methods.
Scriptless JSP pages enhance readability, encourage MVC architecture, and
support better separation of concerns.
Q.
Explain Standard actions in JSP with examples
JSP standard actions provide dynamic functionality
without Java scriptlets.
1. <jsp:include>: Includes a JSP or HTML fragment
at request time.
<jsp:include
page="header.jsp" />
Useful
for modularizing layouts like headers and footers.
2. <jsp:useBean>: Instantiates or accesses a
JavaBean.
<jsp:useBean id="user"
class="com.model.User" scope="request" />
3. <jsp:setProperty>: Sets JavaBean properties
automatically based on request parameters. <jsp:setProperty name="user" property="*" />
These standard actions support reusability,
JavaBean integration, and clean architecture in JSP pages.
No comments:
Post a Comment