Course Unit: Backend Development Using Java
Topic: Servlet Interface and Servlet Classes Individual
Assignment Type: Theory and Practical
PART A: THEORY QUESTIONS
Question 1
a) Define a Servlet in Java.
A Servlet is a Java program that runs on a server to handle client requests and generate
dynamic responses.
b) Explain the role of the Servlet Interface.
The Servlet Interface ([Link]) is the central abstraction of the
Servlet API.
It defines the contract that all servlets must implement.
It ensures that the Servlet Container (like Tomcat) can manage the servlet regardless
of how it is specifically implemented.
It provides the structure for the container to initialize the servlet, pass requests to it, and
eventually destroy it.
c) List and describe the servlet lifecycle methods.
A servlet's life is managed by the container through three primary methods:
1. Init (ServletConfig config): Called exactly once when the servlet is first loaded. It is
used for initialization tasks (e.g., opening a database connection).
2. service (ServletRequest req, ServletResponse res): Called for every request. It
determines the type of request and dispatches it to the appropriate handler.
3. destroy (): Called once before the servlet is removed from service. This is where you
perform cleanup (e.g., closing files or connections).
Question 2
a) What is Generic Servlet?
Generic Servlet is an abstract class that implements the Servlet interface. It provides a
base implementation for all methods except the service () method, making it easier to
write a servlet from scratch.
b) Explain why Generic Servlet is protocol independent.
It is considered protocol-independent because it does not contain specific support for
HTTP. It handles requests using the generic ServletRequest and ServletResponse
objects, meaning it could theoretically be used with other protocols (like FTP or SMTP)
if a compatible container existed.
c) State advantages of using Generic Servlet.
Simplicity: You only need to override the service() method to create a functional
servlet.
Code Reusability: It handles the boilerplate code for init(), destroy(), and
getServletConfig().
Flexibility: It allows you to create servlets for non-HTTP protocols.
Question 3
a) Define HttpServlet.
HttpServlet is an abstract class that extends GenericServlet specifically for the HTTP
protocol. It provides a more specialized environment for web development by handling
HttpServletRequest and HttpServletResponse objects.
b) List and explain HTTP methods supported by HttpServlet.
HttpServlet provides "do" methods that correspond to standard HTTP verbs:
doGet(): Used to retrieve data from a server.
doPost(): Used to send data to a server (e.g., form submissions).
doPut(): Used for "uploading" or replacing a file/resource.
doDelete(): Used to remove a resource from the server.
doOptions()/doHead(): Used for metadata and communication requirements.
d) Why is HttpServlet commonly used?
It is the industry standard because nearly all web applications run on the HTTP protocol. It
offers:
Automatic Dispatching: It automatically routes requests to the correct "do" method
(like doGet or doPost) based on the request type.
Rich Features: It provides easy access to HTTP-specific features like cookies,
sessions, and headers.
PART B: PRACTICAL PrintWriter out = [Link]();
IMPLEMENTATION
[Link]("<html>");
Question 4
[Link]("<head><title>Welcome
Servlet Interface Implementation Servlet</title></head>");
[Link]("<body style='font-family:
Create a servlet implementing Servlet
Arial,sans-serif; text-align:center; margin-top:50px;
interface that displays a welcome
"+ "background: linear-gradient(to right,
message. #1e3c72, #2a5298); color:#fff;'>");
package [Link]; [Link]("<h2>Welcome to My
Website!</h2>");
import [Link];
[Link]("<p>This servlet implements the
import [Link];
<b>Servlet</b> interface directly.</p>");
import [Link];
[Link]("</body>");
import [Link];
[Link]("</html>");
import [Link];
}
import [Link];
@Override
import [Link];
public void destroy() {
public class WelcomeServlet implements Servlet {
[Link]("WelcomeServlet
private ServletConfig config; destroyed");
@Override }
public void init(ServletConfig config) throws @Override
ServletException {
public ServletConfig getServletConfig() {
[Link] = config;
return config;
[Link]("WelcomeServlet
}
initialized");
@Override
}
public String getServletInfo() {
@Override
return "WelcomeServlet: displays a welcome
public void service(ServletRequest request,
message";
ServletResponse response)
}
throws ServletException, IOException {
}
[Link]("text/html");
[Link]("username", username);
RequestDispatcher rd =
[Link]("[Link]");
[Link](request, response);
}
Question 5:
[Link]
GenericServlet Implementation Create a
<!DOCTYPE html>
servlet extending GenericServlet that <html lang="en">
accepts a username, password and <head>
displays a greeting together with the one <meta charset="UTF-8">
who is logged in. <meta name="viewport" content="width=device-
width, initial-scale=1.0">
[Link] <title>Login</title>
<style>
package [Link];
*{
import [Link]; box-sizing: border-box;
import [Link]; margin: 0;
padding: 0;
import [Link];
font-family: Arial, sans-serif;
import [Link];
}
import [Link]; body {
import [Link]; display: flex;
justify-content: center;
align-items: center;
public class LoginServlet extends GenericServlet {
height: 100vh;
@Override background: linear-gradient(to right, #1e3c72,
#2a5298);
public void service(ServletRequest request,
color: #fff;
ServletResponse response)
}
throws ServletException, IOException { .login-container {
String username = background: rgba(0, 128, 0, 0.2);
[Link]("username"); padding: 30px;
border-radius: 15px;
String password =
[Link]("password"); width: 90%;
max-width: 400px;
box-shadow: 0 8px 20px rgba(0, 0, 0, 0.3); <h2>Login</h2>
text-align: center; <form action="LoginServlet" method="post">
} <input type="text" name="username"
placeholder="Username" required>
h2 {
<input type="password" name="password"
margin-bottom: 20px; placeholder="Password" required>
} <input type="submit" value="Login">
input[type="text"], </form>
input[type="password"] { </div>
width: 100%; </body>
padding: 12px; </html>
margin: 10px 0;
border: none; [Link]
border-radius: 8px; <%@ page contentType="text/html;charset=UTF-8"
language="java" %>
}
<!DOCTYPE html>
input[type="submit"] {
<html lang="en">
width: 100%;
<head>
padding: 12px;
<meta charset="UTF-8">
margin-top: 15px;
<meta name="viewport" content="width=device-
border: none;
width, initial-scale=1.0">
border-radius: 8px;
<title>Welcome</title>
background: #00b894;
<style>
color: #fff;
body {
font-weight: bold;
display: flex;
cursor: pointer;
justify-content: center;
transition: 0.3s;
align-items: center;
}
min-height: 100vh;
input[type="submit"]:hover {
margin: 0;
background: #00d084;
font-family: 'Arial', sans-serif;
}
background: linear-gradient(to right, #1e3c72,
@media (max-width: 480px) { #2a5298); /* blue gradient */
.login-container { color: #fff;
padding: 20px; }
} .welcome-container {
} background: rgba(0, 128, 0, 0.2); /* transparent
green card */
</style>
padding: 40px;
</head>
border-radius: 15px;
<body>
max-width: 500px;
<div class="login-container">
text-align: center;
box-shadow: 0 8px 20px rgba(0, 0, 0, 0.3);
h2 {
font-size: 2em;
margin-bottom: 15px;
p{
font-size: 1.2em;
Question 6
}
HttpServlet Implementation Create an
@media (max-width: 480px) {
HttpServlet using doGet() that displays
.welcome-container { date and time.
padding: 20px; package [Link];
} import [Link];
h2 { import [Link];
font-size: 1.5em; import [Link];
} import [Link];
p{ import [Link];
font-size: 1em; import [Link];
} import [Link];
} import [Link];
</style>
</head> public class DateTimeServlet extends HttpServlet {
<body>
<div class="welcome-container"> @Override
<h2>Welcome, <%= protected void doGet(HttpServletRequest request,
[Link]("username") %>!</h2> HttpServletResponse response)
<p>You are logged in as <b><%= throws ServletException, IOException {
[Link]("username") %></b></p>
[Link]("text/html");
</div>
PrintWriter out = [Link]();
</body>
LocalDateTime now = [Link]();
</html>
DateTimeFormatter formatter =
[Link]("EEEE, MMMM dd, yyyy
HH:mm:ss");
String formattedDateTime = [Link](formatter);
[Link]("<!DOCTYPE html>");
[Link]("<html lang='en'>");
[Link]("<head>");
[Link]("<meta name='viewport'
content='width=device-width, initial-scale=1.0'>");
[Link]("<title>Date & Time</title>");
[Link]("<style>");
[Link]("body { display:flex; justify-
content:center; align-items:center; min-height:100vh; " +
"font-family:Arial,sans-serif; margin:0;
background: linear-gradient(to right, #1e3c72, #2a5298);
color:#fff; text-align:center; }");
[Link](".datetime-container { background:
rgba(0,128,0,0.2); padding:30px; border-radius:15px;
box-shadow:0 8px 20px rgba(0,0,0,0.3); }");
[Link]("h2 { font-size:2em; margin-
bottom:15px; }");
[Link]("p { font-size:1.2em; }");
[Link]("@media(max-width:480px){ .datetime-
container{ padding:20px; } h2{ font-size:1.5em; } p{
font-size:1em; } }");
[Link]("</style>");
[Link]("</head>");
[Link]("<body>");
[Link]("<div class='datetime-container'>");
[Link]("<h2>Current Date and Time</h2>");
[Link]("<p>" + formattedDateTime + "</p>");
[Link]("</div>");
[Link]("</body>");
[Link]("</html>");
}
Question 7
Create a comparison table between Servlet Interface, GenericServlet, and HttpServlet.
Feature Servlet Interface GenericServlet HttpServlet
Hierarchy Root interface Implements Servlet Extends GenericServlet
Protocol Protocol-independent Protocol-independent Specifically for HTTP
Methods Must implement all 5 Only service() is Overrides doGet(),
(init, service, etc.) mandatory doPost(), etc.
Complexity High (more boilerplate Medium Low (most convenient)
code)
Usage Rarely used directly Used for non-HTTP Industry standard for
protocols web apps
Question 8
Explain real-world applications of servlets.
Servlets are the "engine room" of many Java-based web systems. They handle the logic that
happens between a user clicking a button and the database saving information. Common uses
include:
1. Form Processing: Handling user input from login screens, registration forms, or
search bars.
2. E-commerce Engines: Managing shopping carts, calculating totals, and processing
payments.
3. Content Management: Dynamically generating HTML pages based on data stored in
a database (like MariaDB/MySQL).
4. API Gateways: Serving as the backend for mobile apps by sending back data in
formats like JSON.