SERVLET
Working of Servlet-Based Web Application (Client to Server
to Client)
When a client, such as a user using a web browser, initiates a request by entering a URL or
submitting a form, an HTTP request is generated and sent over the internet to the web
server. This request contains all necessary information such as the request method (GET or
POST), headers, and possibly form data.
Once the request reaches the web server (such as Apache Tomcat), the server listens for and
receives this incoming request. It then analyzes the URL pattern and determines which
servlet is configured to handle that specific request. If a match is found, the server forwards
the request to the appropriate servlet.
If the servlet has not yet been loaded into memory, the server first loads and initializes it.
Then, the servlet processes the request. During this phase, the servlet can extract any data
sent by the client (like form inputs), perform logic or calculations, and interact with the
database or backend services as needed.
After completing the processing, the servlet generates a response. This response typically
contains HTML content to be displayed on the user's browser, or sometimes other data
formats like JSON or XML. Once the response is ready, the servlet sends it back to the server.
Finally, the server forwards this response to the client’s browser. The browser receives the
response and displays the output to the user
What is a Servlet in Java?
A Servlet is a Java class used to build web applications. It runs on the server side and handles
client requests (usually from a web browser) and generates responses (usually in the form of
HTML or JSON).
1-To create dynamic web pages based on client requests.
2- To handle form submissions from HTML pages.
3- To process URL parameters (query parameters).
4- To connect with databases and return dynamic data.
SERVLET HEIRARCHY –
javax.servlet.Servlet (Interface)
↳ javax.servlet.GenericServlet (Abstract Class)
↳ javax.servlet.http.HttpServlet (Abstract Class)
GenericServlet-
GenericServlet is an abstract class that provides a protocol-independent implementation of
the Servlet interface. To reduce boilerplate code by providing default implementations for
most Servlet interface methods.
To let you focus only on implementing the service() method when creating your custom
servlet
Example -
public class MyGenericServlet extends GenericServlet {
@Override
public void service(ServletRequest req, ServletResponse res)
} }
HttpServlet-
HttpServlet is an abstract class in the javax.servlet.http package that provides methods to
handle HTTP requests (GET, POST, PUT, DELETE, etc.).It extends GenericServlet, making it a
protocol-specific (HTTP-only) servlet
eg -
public class MyHttpServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res)
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res)
etc...
| Method | Description |
| ------------- | ---------------------------- |
| `doGet()` | Handles HTTP GET requests |
| `doPost()` | Handles HTTP POST requests |
| `doPut()` | Handles HTTP PUT requests |
| `doDelete()` | Handles HTTP DELETE requests |
| `doHead()` | Handles HEAD requests |
| `doOptions()` | Lists supported HTTP methods |
| `doTrace()` | Used for diagnostic purposes |
----------------------------------------------------------------------------------------------------------------
What is a Query Parameter?
A query parameter is a key-value pair sent in the URL after a ? character.
Example URL:
http://localhost:8080/myapp/search?username=xyz&pass=123
username=xyz and pass=123 are query parameters.
The URL is calling the /search servlet.
? separates the path from the query string.
& separates multiple query parameters.
How to Get Query Parameters in a Servlet
You can use the HttpServletRequest object to extract query parameters.
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String keyword = request.getParameter("keyword");
String sort = request.getParameter("sort");
PrintWriter out = response.getWriter();
out.println("Search keyword: " + keyword);
out.println("Sort order: " + sort);
Servlet Lifecycle –
1. Loading and Instantiation
2. Initialization (init() method)
3. Request Handling (service() method)
4. Destruction (destroy() method)
The servlet lifecycle begins when the server loads the servlet class into memory and creates
an instance of it—this is called loading and instantiation. After that, the servlet container
calls the init() method only once to perform any required startup operations, initialization
tasks like setting up database connections or reading configuration files. Once the servlet is
initialized, it is ready to handle requests. For every client request, the container calls the
service() method, which then decides whether to call doGet(), doPost(), or other methods
based on the type of request (GET, POST, etc.). Finally, when the servlet is no longer
needed—such as when the server is shutting down or the application is undeployed—the
container calls the destroy() method to allow cleanup of resources before the servlet object
is removed from memory.
Welcome File List in Servlet (web.xml)
In a Java web application, the welcome file list is used to define the default page that should
be loaded when a user visits a web application without specifying any file name in the URL.
When you visit the app The server looks for files like index.html, index.jsp, etc., based on the
welcome-file-list defined in web.xml.
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>home.jsp</welcome-file>
</welcome-file-list>
The container checks the files in the order listed.
If index.html exists, it is shown first.
If not, it checks for index.jsp, then home.jsp, and so on.
If none exist, it may show a 404 error or a directory listing (based on settings).
Load on Startup in Servlet (Detailed Explanation)
In a Java web application, load-on-startup is a configuration element in web.xml that tells
the servlet container when to load a servlet — at server startup
By default, servlets are loaded means they are created and initialized only when the first
request comes. But if you want a servlet to be created and initialized as soon as the server
starts then we will use load on startup.
Tage for web.xml file :
<load-on-startup>1</load-on-startup>
Example :
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.example.MyServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
If you give a positive or zero number (0, 1, 2, etc.), the servlet is loaded at server startup.
• Lower numbers load first. 0 loads before 1.
If load-on-startup is missing or negative, the servlet is loaded when the first request comes.
servelet will not be loaded or instanciated
Send Redirect
sendRedirect() is a method in the HttpServletResponse class used to redirect the client
(browser) to a different URL — to an external website servers. It instructs the browser to
make a new HTTP request to a different URL.
Syntax : response.sendRedirect("newURL");
How does id works:
A client sends a request to Servlet A.
Servlet A uses response.sendRedirect("newurl");.
The browser receives a response with status code 302 (redirect).
The browser then sends a new request to newurl
RequestDispatcher
In servlets, RequestDispatcher is an interface used to forward a request to another resource
like another servlet on the server side
It allows communication between server-side components without changing the URL in the
browser.
Syntax:
1. Get RequestDispatcher:
RequestDispatcher rd = request.getRequestDispatcher("/url-pattern");
2. Forward:
rd.forward(request, response);
Example : LOGIN SENARIO
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String user = request.getParameter("username");
String pass = request.getParameter("password");
if (user.equals("admin") && pass.equals("123")) {
RequestDispatcher rd = request.getRequestDispatcher("welcome.jsp");
rd.forward(request, response); // forward to welcome.jsp
} else {
response.getWriter().println("Invalid credentials");
}
ServletContext
ServletContext is like a common storage area for your whole web application. It is provided
by the server (like Tomcat), and all servlets can use it to share data with each other.
It helps the in:
Sharing Data: You can store something (like a variable or object) in the ServletContext, and
any servlet access it. Think of it as a global application object that all parts of your web app
can use to talk to each other.
Example :
Reading Context Param from web.xml
<context-param>
<param-name>appName</param-name>
<param-value>Student Portal</param-value>
</context-param>
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
IOException {
String name = getServletContext().getInitParameter("appName");
response.getWriter().println("Application Name: " + name);
Example 2:
Store , share and access the student object via context
@WebServlet("/storeStudent")
public class StoreStudentServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Student s = new Student(101, "Ajit");
getServletContext().setAttribute("studentObj", s); } }
@WebServlet("/getStudent")
public class GetStudentServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Student s = (Student) getServletContext().getAttribute("studentObj");
PrintWriter out = response.getWriter();
if (s != null) {
out.println("Student ID: " + s.getId());
out.println("Student Name: " + s.getName());
} else {
out.println("No student found in ServletContext.");
}
ServletConfig
ServletConfig is an interface provided by the Servlet API that allows you to pass initialization
parameters to a specific servlet from the web.xml file.
It is created by the servlet container for each servlet separately and helps in servlet-specific
configuration. Sometimes, you need to pass custom data to a servlet (like an email address,
DB URL, etc.) without hardcoding it in Java. You can define such data in web.xml and read it
using ServletConfig.
Eg –
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.example.MyServlet</servlet-class>
<init-param>
<param-name>adminEmail</param-name>
<param-value>admin@example.com</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/my</url-pattern>
</servlet-mapping>
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
IOException {
ServletConfig config = getServletConfig();
String email = config.getInitParameter("adminEmail");
response.setContentType("text/html");
response.getWriter().println("Admin Email is: " + email);
}
What Are Cookies?
A cookie is a small piece of data stored on the client (browser) and sent back to the server
with each request.
In Servlets, cookies are used to store user-specific information like Login sessions
Method Description
new Cookie(name, value) Creates a cookie
response.addCookie(cookie) Sends cookie to client
request.getCookies() Reads cookies from client
cookie.getName() Gets cookie name
cookie.getValue() Gets cookie value
How Cookie Works:
• First request: You come as a stranger
• Server gives you a cookie: “username = Ajit”
• Next request: Your browser sends back that cookie
• Server recognizes you: “Welcome back Ajit!”
Eg:
public class FirstServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Cookie ck = new Cookie("username", "Ajit");
ck.setMaxAge(60 * 60);
response.addCookie(ck);
response.getWriter().println("Cookie Created and Sent to Browser<br>");
response.getWriter().println("<a href='second'>Go to Second Servlet</a>");
}}
public class SecondServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Cookie[] cookies = request.getCookies();
boolean found = false;
if (cookies != null) {
for (Cookie c : cookies) {
if (c.getName().equals("username")) {
String name = c.getValue();
response.getWriter().println("Welcome back, " + name);
found = true;
if (!found) {
response.getWriter().println("No cookie found!");
}
What is HttpSession?
HttpSession is an interface provided by the Servlet API to manage user sessions on the
server-side.
When a user visits your web application, the server creates a session object to store user-
specific data (like login info, cart, preferences) for that user.
Unlike cookies (stored in the browser), HttpSession stores data on the server, and only
sends a session ID to the browser.
Method Description
getSession() Returns existing session or creates new
getSession(true) Same as above (default)
getSession(false) Returns session if exists, else null
session.setAttribute("key", value) Stores data in session
session.getAttribute("key") Retrieves data from session
session.invalidate() Destroys the session
session.setMaxInactiveInterval(seconds) Sets session timeout
EG-
public class LoginServlet extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException {
PrintWriter out = res.getWriter();
String user = req.getParameter("username");
String pass = req.getParameter("password");
if(user.equals("ajit") && pass.equals("1234")) {
HttpSession session = req.getSession(); // Creates session
session.setAttribute("username", user); // Store data
out.println("Login successful!<br>");
out.println("<a href='profile'>Go to Profile</a>");
} else { out.println("Invalid credentials");}}}
public class ProfileServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException {
PrintWriter out = res.getWriter();
HttpSession session = req.getSession(false); // Don't create new session
if (session != null) {
String user = (String) session.getAttribute("username");
if (user != null) {
out.println("Welcome, " + user);
} else {
out.println("No user found in session.");
} else {
out.println("Session expired or not found.");
}}}
public class LogoutServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException {
HttpSession session = req.getSession(false);
if (session != null) {
session.invalidate(); // Ends the session
res.getWriter().println("Logged out successfully.");