Servlet technology
Servlet technology
---------------------------------
Tech stack?
Desigining a web application involves the tasks like
displaying the data sent from the server, handling client
side operations, handling server side operations and
handling database operations.
To ensure the smooth execution of these operations, we
use a combination of programming languages, tools and
frameworks, called a tech stack.
The tech stack, is visualized as two parts.
1. front end: refers to the technologies used for
interaction with the user.
2. back end: refers to the technologies used on the
server for processing the user inputs and interacting
with the database.
some of the tech stacks are,
MERN(MonogDB-Express.js-React JS-Node.js)
MEAN(MongoDB-Express.js-Angular-Node.js)
LAMP(Linux-Apache-MySQL-PHP)
MongoDB:
MongoDB is an open source document oriented
database written in C++.
Data in MongoDB is stored in documents, with in a
collection, as a set of name-value pairs.
Express.js:
Express.js is a lightweight application development
framework.
Express.js is used for back-end development.
Angular:
Angular is an open source Javascript framework
developed by Google, for building both mobile and web
applications.
It is a good framework for rapid front-end development.
Node.js:
Node.js is a server-side, open source Javascript
execution environment.
It is built on Google chrome’s V8 Javascript runtime.
React JS:
React is an open source Javascript library/framework
developed by facebook, for building both mobile and
web applications.
It is a good framework for rapid front-end development.
out.println("<html>");
out.println("<body>");
out.println("<h2> Welcome to Servlet Programming
</h2>");
out.println("</body>");
out.println("</html>");
out.close();
}
}
<servlet-mapping>
<servlet-name>example</servlet-name>
<url-pattern>/serv</url-pattern>
</servlet-mapping>
</web-app>
HTTP methods:
while clients are communicating with the
servers, the clients like browsers will use some
standard request types called HTTP methods.
The HTTP methods, defines what action should
be taken by the server, when a client makes a
request.
There are 7 HTTP methods.
GET
POST
PUT
DELETE
PATCH
HEAD
OPTIONS
The client(browser) uses request type as GET, to retrieve the
data or a file from the server, without making any changes
to the server.
The client uses request type as POST, to send the data to
the server. Typically it is used to create a new resource in
the server.
While sending the sensitive data like emails, credit card
numbers, passwords, OTP’s etc, to the server, the client
uses the request type as POST.
The client uses request type as PUT, to update or replace an
existing data on the server.
The client uses request type as DELETE, to delete a resource
from the server.
GET : Read
POST : Create
PUT : Update
DELETE : Delete
HttpServlet class:
HttpServlet is an abstract class, which extends
GenericServlet class.
GenericServlet class has an abstract method service(),
which is a life cycle method and HttpServlet class has
overridden this service() method.
HttpServlet class does not contain abstract methods, but the
class is abstract class.
In Java, you can define a class as abstract class, without
abstract methods.
HttpServlet class has defined methods to handle the
different HTTP request types, like
doGet(req,res): To handle HTTP GET request
doPost(req,res): To handle HTTP POST request
doPut(req,res): To handle HTTP PUT request
doDelete(req,res): To handle HTTP DELETE request
doPatch(req,res): To handle HTTP PATCH request
doHead(req,res): To handle HTTP HEAD request
doOptions(req,res):To handle HTTP OPTIONS request
In short the above seven methods are called doXxx()
methods.
The functionality defined in the doXxx() methods, it not upto
the mark. It means, this logic can’t handle the requests
properly.
So, to denote that HttpServlet class as incomplete class, it is
given as abstract class.
In our web application development, we create our servlet
classes mostly by extending HttpServlet class. Because, we
can define the logics in different methods like
doGet()/doPost(), so the servlet becomes easily
understandable to the other developers.
For each request, the servlet container calls service() [life
cycle method] and it will dispatch the request to
doGet()/doPost(), based on request type.
login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login Page</title>
</head>
<body>
<form action="./signin" method="post">
<table>
<tr>
<td>Username </td>
<td> <input type="text" name="username"> </td>
</tr>
<tr>
<td>Password </td>
<td> <input type="password" name="password"> </td>
</tr>
</table>
<button type="submit">submit</button>
</form>
</body>
</html>
LoginServlet.java
package com.ashokit.example;
import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
}
web.xml
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet("/signin")
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req,
HttpServletResponse resp) throws ServletException,
IOException {
</body>
</html>
header.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<center>
<font color='green' size="10">Ashokit</font>
</center>
</body>
</html>
footer.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<center>
<h2> © Hyderabad, 2024 </h2>
</center>
</body>
</html>
CreateProfileServlet.java
package pack1;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.time.LocalDate;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet("/create")
public class CreateProfileServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req,
HttpServletResponse resp) throws ServletException,
IOException {
pstmt.executeUpdate();
pstmt.close();
}
catch(Exception ex) {
ex.printStackTrace();
}
finally {
try {
if(pstmt != null)
pstmt.close();
if(conn!=null)
conn.close();
}
catch(Exception ex) {
ex.printStackTrace();
}
}
}
ViewProfileServlet.java
package pack1;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet("/view")
public class ViewProfileServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req,
HttpServletResponse resp) throws ServletException,
IOException {
RequestDispatcher dispatcher1 =
req.getRequestDispatcher("header.html");
dispatcher1.include(req, resp);
out.println("<hr>");
ResultSet rs = pstmt.executeQuery();
if(rs.next()) {
out.println("<h3>");
out.println("Firstname : " +
rs.getString(1));
out.println("<br>");
out.println("Lastname : " +
rs.getString(2));
out.println("<br>");
out.println("DateofBirth : " +
rs.getString(3));
out.println("<br>");
out.println("gender : " +
rs.getString(4));
out.println("<br>");
out.println("</h3>");
}
out.println("<hr>");
RequestDispatcher dispatcher2 =
req.getRequestDispatcher("footer.html");
dispatcher2.include(req, resp);
rs.close();
}
catch(Exception ex) {
ex.printStackTrace();
}
finally {
try {
if(pstmt != null)
pstmt.close();
if(conn!=null)
conn.close();
}
catch(Exception ex) {
ex.printStackTrace();
}
}
out.close();
}
}
forwarding vs redirecting:
Both of these are for servlet to servlet
communication. but they have some differences.
1. forwarding is done without any information to the
client. But redirection provides information to the
client.
2. In forwarding, the same original request is
forwarded from servlet1 to servlet2. In Redirection,
the client/browser will make a new request to
servlet2.
3. In forwarding, the same original request is
forwarded to servlet2. So, the parameters are also
forwarded. But in redirection, new request is
created. So, the parameters in the original request
are not redirected.
4. For request forwarding, both the servlet classes
must be on same server. For redirection, both the
servlet classes may on the same server or on
different servers.
5. For forwarding, we call
dispatcher.forward(req,resp). For redirection, we call
resp.sendRedirect(“url”).
100 Continue
. when a client is going to send a large file/image in the request body,
first the client will send a request and tells the server that I am going to send a
large data/file in the request.
. The server responds with status code 100 continue, then the client will
send the large file/data in the request body.
200 Ok
.The server sends status code 200 Ok, if the request was processed
successfully and if the server has returned the response data.
201 Created
.The server responds with 201 Created, if the request was successful and
if a new resource is created at the server, because of this request.
204 No Content
.The server responds with 204 No Content, if the request was successful,
but the server is not returning any content.
301 Moved Permanently
.The server responds with 301 Moved Permanently, if the request resource
has been permanently moved to a new URL.
302 Found
.The server responds with 302 Found, if the requested resource is
temporarily available at a different URL.
400 Bad Request
.The server responds with 400 Bad Request, if the server is unable to
understand the request due to invalid syntax.
401 Unauthorized
.The server responds with 401 Unauthorized, if the client is sending the
request to a protected resource, without authorization.
404 Not Found
.The server responds with 404 Not Found, if the server can not find the
request resource.
405 Method NotAllowed
.The server responds with 405 Method Not Allowed, if the request method is
not supported by the server.
500 Internal Server Error
.The server responds with 500 Internal Server Error, if the server has
encountered a generic error.
503 Service Unavailable
.The server responds with 503 Service Unavailable, due to overload of
requests.
Session Management
HTTP is a stateless protocol.
stateless means, every request from a client to a server is treated as an
independent request. The server does not rememeber previous interactions
with the client.
Suppose, if a user is sending multiple requests, the server treats like each
request is coming from a new user.
In most web applications, keeping track of information about the user across
the mulitple requests is required.
So, session management techniques are used.
Session management is a process, used to maintain stateful interactions
between the client and server in web applications, despite of the stateless
nature of HTTP.
Suppose, in E-commerce applications, if session management technique is not
used, then when a user is moving from one page another page, the server
treats that user as a new user and the cart will be reset with every request. So,
a user can not purchase multiple items at a time.
If session management technique is used, the server can track and manage
the user and the items added to the cart when a user is moving between
pages. Which means, the server remembers the user’s data across mulitple
requests.
The servlets technology has provided HTTP Cookies and HttpSession api to
manage the sessions.
HTTP Cookies:
-------------
HttpSession API
removeAttribute(key) method.
setMaxInactiveInterval() method.
for example,
session.setMaxInactiveInterval(120); // 2 minutes