1) Introduction to Servlet (Definition)
A Servlet is a server-side Java program that runs on a web server and is used to handle client requests and generate dynamic web responses.
👉 It works by receiving requests from the client (browser), processing them, and sending back the response (HTML, data, etc.).
Here is your 7-mark, easy but detailed answer 👇
2) Explain Servlet Interface
Definition
The Servlet Interface is a part of Java Servlet API that defines the life cycle methods which must be implemented by all servlets.
It is available in the package javax.servlet.
Methods of Servlet Interface
1) init()
Called only once when servlet is initialized
Used for initial setup (loading resources, database connection)
public void init(ServletConfig config) throws ServletException {
// initialization code
}
2) service()
Called for every client request
Responsible for processing request and generating response
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
// request handling
}
3) destroy()
Called once before servlet is removed
Used to release resources (close DB, files)
public void destroy() {
// cleanup code
}
4) getServletConfig()
Returns ServletConfig object
Used to get initialization parameters
public ServletConfig getServletConfig() {
return config;
}
5) getServletInfo()
Returns information about servlet
(Author, version, etc.)
public String getServletInfo() {
return "Simple Servlet";
}
Servlet Life Cycle (Short Flow)
Servlet loaded
init()calledservice()called multiple timesdestroy()called
Conclusion
Servlet Interface defines the structure and life cycle of a servlet, and all servlets must implement its methods either directly or through classes like GenericServlet or HttpServlet.
3) Explain HttpServlet Class and Its Methods
The HTTP servlet class extends GenericServlet class.
It is commonly used by programmers when developing a servlet.
That receives and process HTTP request because it is having HTTP protocol functionality.
It also implemented the servlet interface it is an abstract class that provides request and response functionality.
This class implements a various method and also other methods that are inherited from the GenericServlet class.
This class provides following methods:
1) doGet( )
2) doPost( )
3) doDelete( )
4) doPut( )
5) doOption( )
6) doTrace( )
Important Methods of HttpServlet
1) doGet()
Handles HTTP GET request
Used to request data from server
protected void doGet(HttpServletRequest req, HttpServletResponse res)
2) doPost()
Handles HTTP POST request
Used to send data to server (form submission)
protected void doPost(HttpServletRequest req, HttpServletResponse res)
3) doPut()
Handles HTTP PUT request
Used to update data on server
4) doDelete()
Handles HTTP DELETE request
Used to delete data from server
5) doOptions()
Returns supported HTTP methods
6) doTrace()
Used for debugging request/response
Example
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("Hello from Servlet");
}
}
Q.4) Explain Servlet Life Cycle
Definition
The Servlet Life Cycle defines the steps followed by a servlet from
its creation to destruction.
These steps are managed by the web container (server).
Steps of Servlet Life Cycle
1) The server loads the servlet
-
The web server loads the servlet class into memory when it is needed.
2) Server creates an instance of servlet
-
The server creates an object (instance) of the servlet class.
3) Server calls the init() method
-
The
init() method is called only once.
-
It is used to initialize the servlet, like opening database connection.
Syntax:
public void init(ServletConfig config) throws ServletException
4) Server calls the service() method
-
The
service() method is called whenever a client sends a request.
-
It decides which method to call (
doGet(), doPost(), etc.).
Syntax:
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException
5) The request is responded using service()
-
The servlet processes the request and sends response back to the client.
-
This step happens multiple times for multiple requests.
6) Servlet is destroyed using destroy()
-
The
destroy() method is called only once when the servlet is removed.
-
It is used to release resources like closing connections.
Syntax:
public void destroy()
Conclusion
The Servlet Life Cycle ensures that the servlet works properly by managing
its creation, execution, and destruction in a proper sequence.
9) Differentiate Servlet Vs JSP
Point Servlet JSP (Java Server Pages) 1) Nature A Servlet is a Java class used for web development. JSP is an HTML-based page that contains Java code.
2) Coding Style In Servlet, we write more Java code and less HTML. In JSP, we write more HTML and less Java code.
3) Development In Servlet, designing the user interface is difficult. In JSP, designing the user interface is easy.
4) Compilation Servlet is already compiled Java class. JSP is first converted into Servlet and then compiled.
5) Performance Servlet provides better performance. JSP is slightly slower than Servlet.
6) Usage Servlet is mainly used for business logic processing. JSP is mainly used for presentation (UI design).
7) Ease of Use Servlet is complex to write and manage. JSP is easy to write and maintain.
8) Execution Servlet runs directly on the server. JSP is first converted to Servlet and then runs on the server.
9) Modification In Servlet, any change requires recompilation. In JSP, changes are automatically recompiled by server.
10) Readability Servlet code is less readable due to mixed Java and HTML. JSP code is more readable because it looks like HTML.
Conclusion
Servlet is used for logic handling, while JSP is used for designing web pages,
and both are used together in web applications.
Q.10) Explain HttpSession with Example
Definition
HttpSession is a part of the Java Servlet API (in javax.servlet.http package)
that is used to create and maintain a session between client and server.
It allows the server to store user-specific data and track the user across
multiple requests.
Why HttpSession is Required
HTTP is a stateless protocol, which means each request is treated as a new request and
the server does not remember previous interactions.
HttpSession is used to maintain state by storing user data such as login details,
shopping cart items, etc.
Working of HttpSession
When a user sends a request, the server creates a unique session ID.
This session ID is sent to the client (usually stored in cookies).
For every next request, the client sends the same session ID.
The server uses this ID to identify the user and retrieve stored data.
Important Methods of HttpSession
1) setAttribute()
It is used to store data in the session using key-value pair.
Syntax:
session.setAttribute("key", value);
2) getAttribute()
It is used to retrieve stored data from the session.
Syntax:
session.getAttribute("key");
3) removeAttribute()
It is used to remove a specific attribute from the session.
Syntax:
session.removeAttribute("key");
4) invalidate()
It is used to destroy the entire session.
Syntax:
session.invalidate();
5) getId()
It returns the unique session ID.
Syntax:
session.getId();
6) getCreationTime()
It returns the time when session was created.
7) getLastAccessedTime()
It returns the last time the user accessed the session.
Example
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SessionExample extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
// Create or get existing session
HttpSession session = req.getSession();
// Store data in session
session.setAttribute("username", "Admin");
// Retrieve data
String user = (String) session.getAttribute("username");
// Display data
out.println("Welcome " + user);
// Display session ID
out.println("<br>Session ID: " + session.getId());
}
}
Advantages
It helps to maintain user state.
It is secure and easy to use.
It can store any type of object.
Disadvantages
It uses server memory.
It may affect performance if many users are active.
Q.5) Explain HttpServletRequest Interface with any 5 methods.
HttpServletRequest Interface (Definition)
The HttpServletRequest interface is part of the Java Servlet API.
It is used by a servlet to receive and handle client request data
(like form data, parameters, headers, cookies, etc.).
👉 In simple words:
It helps the servlet to read data sent by the browser (client).
Commonly Used Methods (Any 5)
1) getParameter()
Used to get value of a form field.
Returns value as String.
Syntax:
String value = request.getParameter("name");
Example:
String username = request.getParameter("username");
2) getParameterValues()
Used when a parameter has multiple values (like checkbox).
Returns array of String.
Syntax:
String[] values = request.getParameterValues("name");
3) getParameterNames()
Returns all parameter names sent by client.
Useful for dynamic forms.
Syntax:
Enumeration<String> names = request.getParameterNames();
4) getHeader()
Used to get request header information (like browser info).
Returns String value.
Syntax:
String header = request.getHeader("header-name");
Example:
String userAgent = request.getHeader("User-Agent");
5) getMethod()
Returns HTTP method used (GET, POST).
Syntax:
String method = request.getMethod();
>>Servlet example using HttpServletRequest (exam-ready) 👇
Example: Get Form Data using HttpServletRequest
1) HTML Form (index.html)
<!DOCTYPE html>
<html>
<head>
<title>Form Example</title>
</head>
<body>
<form action="MyServlet" method="post">
Name: <input type="text" name="username"><br><br>
City: <input type="text" name="city"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
2) Servlet Program (MyServlet.java)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// Using HttpServletRequest methods
String name = request.getParameter("username");
String city = request.getParameter("city");
String method = request.getMethod();
String userAgent = request.getHeader("User-Agent");
out.println("<h2>Student Details</h2>");
out.println("Name: " + name + "<br>");
out.println("City: " + city + "<br>");
out.println("Method Used: " + method + "<br>");
out.println("Browser Info: " + userAgent);
}
}
Explanation (Easy 4 Points)
HTML form sends data to servlet using POST method
Servlet receives request using HttpServletRequest object
getParameter() is used to read form values
Output is displayed using PrintWriter
Output
👉 When user fills form → Servlet shows:
Name
City
Method (POST)
Browser info
No comments:
Post a Comment