What is a servlet? Explain its lifecycle.
Introducing Servlets
• Servlets are small programs that execute on the server side of a web connection.
• servlets dynamically extend the functionality of a web server.
The Life Cycle of a Servlet
There are three main methods central to the life cycle of a servlet:
➤ init( )
➤ service( )
➤ destroy( )
These methods are implemented by every servlet and are invoked at specific times by the server.
Let us consider a typical user scenario to understand when these methods are called:
1. User sends a request
A user enters a URL into a web browser.
The browser generates an HTTP request for this URL and sends it to the appropriate web server.
2. Server receives the request
The web server receives the HTTP request.
It maps the request to a specific servlet.
If the servlet is not already in memory, it is dynamically loaded into the server’s address space.
3. Initialization: init() method is called
The server calls the init() method of the servlet.
This method is called only once, when the servlet is first loaded into memory.
Initialization parameters can be passed for configuration.
4. Request Handling: service() method is called
The server then calls the service() method.
This method handles the client’s HTTP request and sends a response back.
The service() method is called each time the servlet handles a request.
5. Servlet stays in memory
The servlet remains in the server’s memory and can continue to handle more requests using the service()
method.
6. Destruction: destroy() method is called
Eventually, the server may decide to unload the servlet (based on internal algorithms).
The destroy() method is called to release resources (like file handles, DB connections).
Important data can be saved before destruction.
After that, the servlet object becomes eligible for garbage collection.
Compare servlets and CGI. In terms of servlet, explain the concept of cookies.
Advantages of Servlets over CGI
Servlets offer several advantages compared to CGI (Common Gateway Interface):
1. Better Performance:
o Servlets offer significantly better performance than CGI.
o They are faster and more efficient.
2. No Separate Process Creation:
o Servlets run within the address space of the web server.
o There is no need to create a new process for every client request (unlike CGI), reducing
overhead.
3. Platform Independence:
o Servlets are written in Java, making them platform-independent.
o They can run on any server with a Java-compatible environment.
4. Security:
o The Java Security Manager enforces a set of restrictions to protect server resources.
5. Access to Java Libraries:
o Servlets can access the complete Java class libraries.
o They can easily communicate with applets, databases, and other components via Sockets or RMI
(Remote Method Invocation).
The Cookie Class
The Cookie class is used to create and manage cookies in servlets.
A cookie is a small piece of data stored on the client’s machine.
It is used to maintain state information across multiple requests and is helpful in tracking user activity.
Example Use Case:
Suppose a user visits an online shopping website.
A cookie can be used to store the user's name, address, or other preferences.
This way, the user does not need to re-enter details on every visit.
Creating a Cookie:
To create a cookie, use the following constructor:
Cookie(String name, String value)
Example: Cookie c = new Cookie("username", "John");
Sending a Cookie to the Client:
A servlet sends a cookie to the client using the addCookie() method of the HttpServletResponse interface:
response.addCookie(c);
The cookie is then included in the HTTP response header sent to the browser.
Information Stored in a Cookie:
Each cookie can contain the following:
1. Name – The name of the cookie.
2. Value – The actual data (e.g., user name).
3. Expiration Date –
o Determines when the cookie will be deleted from the user’s machine.
o If not set, the cookie is deleted after the browser session ends.
4. Domain and Path –
o Specify the scope of the cookie (i.e., when it should be sent back to the server).
o The cookie is only sent to the server if the domain and path match the URL being requested.
When Cookies Are Sent Back to the Server:
If the user enters a URL whose domain and path match the stored cookie,
→ The cookie is included in the HTTP request header and sent back to the server.
Otherwise, it is not included.
. Define Swings. Explain key Swing components: JFrame, JPanel, JButton.
✅ Define Swing
Swing is a part of the Java Foundation Classes (JFC) used to create Graphical User Interfaces (GUIs) in Java.
It provides lightweight, platform-independent, and pluggable components such as buttons, labels, text boxes,
and windows. Unlike AWT, Swing components are written entirely in Java, which ensures a consistent look and
feel across platforms.
🔑 Key Swing Components
🔹 1. JFrame
A top-level window with a title bar and borders.
It acts as the main window of a Swing application.
Other components must be added to the content pane of the JFrame.
Syntax:
JFrame frame = new JFrame("My Application");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
Example Explanation:
new JFrame("My Application") creates a window with the given title.
setSize() sets the width and height.
setDefaultCloseOperation() ensures the program exits on close.
setVisible(true) makes the window visible.
🔹 2. JPanel
A lightweight container used to group and organize other components.
Often used inside a JFrame to manage layout using layout managers like FlowLayout, GridLayout, etc.
Syntax:
JPanel panel = new JPanel(); // Creates a panel with default FlowLayout
frame.add(panel); // Adds the panel to the JFrame
Example Explanation:
A JPanel acts like a sub-container inside the JFrame.
Components like buttons or labels are added to this panel.
🔹 3. JButton
A clickable button component that can perform actions.
Used to handle ActionEvents when clicked.
Syntax:
JButton button = new JButton("Click Me");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button was clicked!");
}
});
panel.add(button); // Add button to panel
Example Explanation:
new JButton("Click Me") creates a button with the label.
addActionListener() adds functionality when the button is clicked.
actionPerformed() defines the action to take.
Develop an event-handling example using Button and TextField.
Swing uses the delegation event model for handling events. In this model, a component (like a button) generates
an event, and a listener (like ActionListener) handles it. Below is an example that uses a JButton and a
JTextField to demonstrate event handling.
🔍 Explanation:
JTextField is used to enter or display a line of text.
When the JButton is clicked, an ActionEvent is triggered.
The ActionListener sets new text into the text field.
Describe the Model-View-Controller (MVC) architecture in Swing.
1. Definition
MVC is a design pattern that divides a software component into three interconnected parts:
Model (Data Layer)
View (Presentation Layer)
Controller (Input Handling Layer)
2. Architecture in Swing
Swing implements a modified version called Model-Delegate Architecture:
Component Role in Swing Example Classes/Interfaces
Model Manages data and state logic ButtonModel, DefaultListModel
UI
Combines View + Controller functions ButtonUI, ListUI (extends ComponentUI)
Delegate
3. Key Characteristics
Separation: Model is completely independent from rendering/input
Pluggable UI: Different look-and-feel implementations can be swapped
Event Handling: User interactions modify the model through the delegate
4. Data Flow
1. User interacts with component (e.g., clicks button)
2. UI Delegate (Controller part) processes input
3. Model updates its state
4. UI Delegate (View part) refreshes display based on new model state
Explain the various classes and interfaces present in Servlet API.
✅ Main Packages in Servlet API
1. jakarta.servlet – General servlet functionality.
2. jakarta.servlet.http – Specific to HTTP protocol.
🔹 Core Interfaces in jakarta.servlet
Interface Description
Base interface that all servlets must implement. Declares init(), service(), destroy(),
Servlet
getServletConfig(), and getServletInfo().
ServletRequest Represents the client's request. Lets you get parameters, input stream, attributes, etc.
ServletResponse Represents the servlet’s response to the client. Allows setting content type and writing output.
ServletConfig Provides servlet-specific configuration data like init parameters.
Provides information about the web application environment. Useful for application-wide
ServletContext
parameters and resources.
🔹 Important Classes in jakarta.servlet
Class Description
Abstract class implementing Servlet and ServletConfig. Useful for protocol-independent
GenericServlet
servlets (e.g., not HTTP).
ServletInputStream Used to read binary data from the request.
ServletOutputStream Used to write binary data to the response.
ServletException Indicates a general servlet-related error.
UnavailableException Indicates the servlet is temporarily or permanently unavailable.
🔹 Core Interfaces in jakarta.servlet.http
Interface Description
Extends ServletRequest. Adds HTTP-specific methods like getSession(), getCookies(),
HttpServletRequest
getHeader().
HttpServletResponse Extends ServletResponse. Adds methods like addCookie(), sendRedirect(), setStatus().
HttpSession Manages session info between client and server.
HttpSessionListener Used to monitor session lifecycle events.
🔹 Important Class in jakarta.servlet.http
Class Description
HttpServlet Extends GenericServlet. Common base for all HTTP-based servlets. Handles doGet(), doPost(), etc.
Cookie Represents HTTP cookies. Used for storing small bits of data on the client.
Explain in brief the concept of JSP scriptlets, expressions, and declarations with an
example.
✅ 1. JSP Scriptlets
Purpose: Write Java code (loops, conditions, statements) inside JSP to run every time the page is
requested.
Syntax:
<% Java code here %>
Details:
Scriptlets are inserted inside the _jspService() method in the generated servlet, so the code runs on every
request. Use them to perform calculations, control flow, or manipulate data before output.
Example:
<%
int a = 10;
int b = 20;
int sum = a + b;
if(sum > 20) {
out.println("<p>Sum is greater than 20</p>");
}
%>
<p>The sum is: <%= sum %></p>
✅ 2. JSP Expressions
Purpose: Output the value of a Java expression directly to the webpage.
Syntax:
<%= expression %>
Details:
The expression is automatically converted to string and sent to the client as part of the HTML. It’s like a
shortcut for out.print(expression); inside the JSP.
Example:
<p>Today's date is: <%= new java.util.Date() %></p>
<p>User count: <%= userCount %></p>
✅ 3. JSP Declarations
Purpose: Declare variables or methods that exist at the class level, shared across requests in the servlet.
Syntax:
<%! code %>
Details:
Code inside declarations is placed outside the _jspService() method, as part of the servlet class. Variables
declared here are instance variables, so they maintain their value across requests (unless servlet reloads).
Use with care because of thread safety.
Example:
<%! int visitCounter = 0; %>
<%
visitCounter++;
%>
<p>Page visit count: <%= visitCounter %></p>
📌 Summary Table
Element Syntax Purpose
Scriptlet <% code %> Write Java logic (loops, conditions) executed each request
Expression <%= expr %> Output Java expression result directly to browser
Declaration <%! code %> Declare variables or methods shared across requests (class level)
Explain different types of JDBC drivers.
JDBC drivers are classified into four types based on how they connect Java applications to the database:
1. Type 1 – JDBC-ODBC Bridge Driver
Uses ODBC driver via a bridge.
Platform Dependent.
Deprecated in Java 8+.
Syntax:
java
CopyEdit
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:DSN", "user", "pass");
2. Type 2 – Native-API Driver
Uses native DB client libraries.
Faster than Type 1, but platform dependent.
Needs DB vendor's native library.
Syntax:
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:oci:@DB", "user", "pass");
3. Type 3 – Network Protocol Driver
Uses a middleware server between client and database.
Platform independent.
Suitable for web applications.
Syntax:
Class.forName("com.ddtek.jdbc.openedge.OpenEdgeDriver");
Connection con = DriverManager.getConnection("jdbc:datadirect:openedge://server:port;databaseName=db",
"user", "pass");
4. Type 4 – Thin Driver (Pure Java Driver)
Directly connects to the database using pure Java.
Platform independent & high performance.
No need for native libraries.
Syntax:
Class.forName("com.mysql.jdbc.Driver"); // or "com.mysql.cj.jdbc.Driver"
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/DB", "user", "pass");
✅ Comparison Table:
Type Name Platform Independent Middleware Native Code Example DB
1 JDBC-ODBC Bridge ❌ ❌ ✅ Any ODBC DB
2 Native-API Driver ❌ ❌ ✅ Oracle
3 Network Protocol ✅ ✅ ❌ IDS, Sybase
4 Thin Driver (Pure Java) ✅ ❌ ❌ MySQL, PostgreSQL
Describe the steps for database connectivity using JDBC with programming example.
JDBC (Java Database Connectivity) allows Java programs to connect and interact with databases.
Steps to connect a database using JDBC:
1. Load the JDBC Driver:
Load the driver class for the database (e.g., MySQL, Oracle) so Java can communicate with the database.
Class.forName("com.mysql.cj.jdbc.Driver");
2. Establish Connection:
Use DriverManager to create a connection object with database URL, username, and password.
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydatabase", "root", "password");
3. Create a Statement:
Create a Statement or PreparedStatement object to send SQL commands.
Statement stmt = con.createStatement();
4. Execute SQL Query:
Run SQL commands using execute methods:
o executeQuery() for SELECT (returns ResultSet)
o executeUpdate() for INSERT, UPDATE, DELETE (returns int)
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
5. Process the ResultSet:
Iterate over results if any.
while (rs.next()) {
System.out.println(rs.getString("username"));
}
6. Close the Connections:
Close ResultSet, Statement, and Connection to release resources.
rs.close();
stmt.close();
con.close();
Complete Example:
Demonstrate the concept of Statement, PreparedStatement, and CallableStatement.
Feature Statement PreparedStatement CallableStatement
Executes simple SQL Executes precompiled SQL with Executes stored procedures
Purpose
queries parameters in DB
Feature Statement PreparedStatement CallableStatement
Statement stmt = PreparedStatement pstmt = CallableStatement cstmt =
Syntax
con.createStatement(); con.prepareStatement(sql); con.prepareCall(sql);
Parameterized SQL (with ?
SQL Type Dynamic, plain SQL Call stored procedures
placeholders)
Faster for repeated execution Used specifically for stored
Performance Slower for repeated queries
(precompiled) procedures
Vulnerable to SQL
Security Safer, handles parameters properly Safer for procedure calls
Injection
Example for each:
Statement Example:
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users WHERE status='active'");
PreparedStatement Example:
String sql = "SELECT * FROM users WHERE username = ?";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, "john");
ResultSet rs = pstmt.executeQuery();
CallableStatement Example:
Suppose you have a stored procedure named getUserById:
CREATE PROCEDURE getUserById(IN userId INT)
BEGIN
SELECT * FROM users WHERE id = userId;
END
Java code to call this procedure:
CallableStatement cstmt = con.prepareCall("{call getUserById(?)}");
cstmt.setInt(1, 10);
ResultSet rs = cstmt.executeQuery();