file_1683178465_0003311_servlet
file_1683178465_0003311_servlet
file_1683178465_0003311_servlet
1
Servlet
Servlet technology is used to create web application (resides at
server side and generates dynamic web page).
There are many interfaces and classes in the servlet API such
as Servlet, GenericServlet, HttpServlet, ServletRequest,
ServletResponse etc.
2
What is a Servlet?
3
4
What is web application?
7
CGI(Commmon Gateway Interface)
8
Disadvantages of CGI
9
Advantage of Servlet
10
Web Terminology
11
Website
Website is a collection of related web pages that may contain
text, images, audio and video. The first page of a website is
called home page. Each website has specific internet address
(URL) that you need to enter in your browser to access a
website.
Website is hosted on one or more servers and can be accessed
by visiting its homepage using a computer network. A website
is managed by its owner that can be an individual, company or
an organization.
A website can be of two types:
Static Website
Dynamic Website
12
Static website
13
Dynamic website
14
Servlet API
16
Interfaces in javax.servlet.http package
17
Classes in javax.servlet.http package
19
Methods of Servlet interface
20
GenericServlet class
GenericServletclass
implements Servlet, ServletConfig and Serializable interface
s. It provides the implementation of all the methods of these
interfaces except the service method.
GenericServlet class can handle any type of request so it is
protocol-independent.
You may create a generic servlet by inheriting the
GenericServlet class and providing the implementation of the
service method.
21
Methods of GenericServlet class
ere are many methods in GenericServlet class. They are as follows:
public void init(ServletConfig config) is used to initialize the servlet.
public abstract void service(ServletRequest request, ServletResponse response) provides
service for the incoming request. It is invoked at each time when user requests for a servlet.
public void destroy() is invoked only once throughout the life cycle and indicates that servlet
is being destroyed.
public ServletConfig getServletConfig() returns the object of ServletConfig.
public String getServletInfo() returns information about servlet such as writer, copyright,
version etc.
public void init() it is a convenient method for the servlet programmers, now there is no need
to call super.init(config)
public ServletContext getServletContext() returns the object of ServletContext.
public String getInitParameter(String name) returns the parameter value for the given
parameter name.
public Enumeration getInitParameterNames() returns all the parameters defined in the
web.xml file.
public String getServletName() returns the name of the servlet object.
public void log(String msg) writes the given message in the servlet log file.
public void log(String msg,Throwable t) writes the explanatory message in the servlet log
file and a stack trace. 22
Servlet Example by inheriting the GenericServlet class
import java.io.*;
import javax.servlet.*;
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello generic servlet</b>");
out.print("</body></html>");
}
}
23
HttpServlet class
24
Methods of HttpServlet class
There are many methods in HttpServlet class. They are as follows:
public void service(ServletRequest req,ServletResponse res) dispatches the request to the protected
service method by converting the request and response object into http type.
protected void service(HttpServletRequest req, HttpServletResponse res) receives the request from the
service method, and dispatches the request to the doXXX() method depending on the incoming http request
type.
protected void doGet(HttpServletRequest req, HttpServletResponse res) handles the GET request. It is
invoked by the web container.
protected void doPost(HttpServletRequest req, HttpServletResponse res) handles the POST request. It
is invoked by the web container.
protected void doHead(HttpServletRequest req, HttpServletResponse res) handles the HEAD request.
It is invoked by the web container.
protected void doOptions(HttpServletRequest req, HttpServletResponse res) handles the OPTIONS
request. It is invoked by the web container.
protected void doPut(HttpServletRequest req, HttpServletResponse res) handles the PUT request. It is
invoked by the web container.
protected void doTrace(HttpServletRequest req, HttpServletResponse res) handles the TRACE
request. It is invoked by the web container.
protected void doDelete(HttpServletRequest req, HttpServletResponse res) handles the DELETE
request. It is invoked by the web container.
protected long getLastModified(HttpServletRequest req) returns the time when HttpServletRequest was
last modified since midnight January 1, 1970 GMT.
25
Life Cycle of a Servlet (Servlet Life Cycle)
The web container maintains the life cycle of a
servlet instance. Let's see the life cycle of the
servlet:
Servlet class is loaded.
26
27
28
29
Steps to create a servlet example
There are given 6 steps to create a servlet example. These steps are required for all
the servers.
The servlet example can be created by three ways:
By implementing Servlet interface,
By inheriting GenericServlet class, (or)
By inheriting HttpServlet class
The mostly used approach is by extending HttpServlet because it provides http
request specific method such as doGet(), doPost(), doHead() etc.
Here, we are going to use apache tomcat server in this example. The steps are as
follows:
Create a directory structure
Create a Servlet
Compile the Servlet
Create a deployment descriptor
Start the server and deploy the project
Access the servlet 30
1)Create a directory structures
The directory structure defines that where to put the different
types of files so that web container may get the information
and respond to the client.
The Sun Microsystem defines a unique standard to be
followed by all the server vendors. Let's see the directory
structure that must be followed to create the servlet.
31
2)Create a Servlet
There are three ways to create the servlet.By implementing the
Servlet interface
By inheriting the GenericServlet class
By inheriting the HttpServlet class
33
3)Compile the servlet
For compiling the Servlet, jar file is required to be loaded. Different Servers
provide different jar files:
Put the java file in any folder. After compiling the java file, paste the class file of
servlet in WEB-INF/classesdirectory.
34
4)Create the deployment descriptor (web.xml file)
The deployment descriptor is an xml file, from which Web Container gets the information about the servet
to be invoked.
The web container uses the Parser to get the information from the web.xml file. There are many xml parsers
such as SAX, DOM and Pull.
There are many elements in the web.xml file. Here is given some necessary elements to run the simple
servlet program.
Web.xml file
<web-app>
<servlet>
<servlet-name>india</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>india</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
35
Description of the elements of web.xml file
There are too many elements in the web.xml file. Here is the illustration of
some elements that is used in the above web.xml file. The elements are as
follows:
<web-app> represents the whole application.
<servlet> is sub element of <web-app> and represents the servlet.
<servlet-name> is sub element of <servlet> represents the name of the
servlet.
<servlet-class> is sub element of <servlet> represents the class of the
servlet.
<servlet-mapping> is sub element of <web-app>. It is used to map the
servlet.
<url-pattern> is sub element of <servlet-mapping>. This pattern is used at
client side to invoke the servlet.
36
5)Start the Server and deploy the project
To start Apache Tomcat server, double click on the startup.bat file under
apache-tomcat/bin directory.
37
How Servlet works?
It is important to learn how servlet works for understanding
the servlet well. Here, we are going to get the internal detail
about the first servlet program.
The server checks if the servlet is requested for the first time.
If yes, web container does the following tasks:
loads the servlet class.
instantiates the servlet class.
calls the init method passing the ServletConfig object
else
calls the service method passing request and response objects
The web container calls the destroy method when it needs to
remove the servlet such as at time of stopping server or
undeploying the project.
38
How web container handles the servlet request?
The web container is responsible to handle the request. Let's see how it
handles the request.
39
What is written inside the public service method?
The public service method converts the ServletRequest object into the HttpServletRequest
type and ServletResponse object into the HttpServletResponse type. Then, calls the service
method passing these objects. Let's see the internal code:
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException
{
HttpServletRequest request;
HttpServletResponse response;
try
{
request = (HttpServletRequest)req;
response = (HttpServletResponse)res;
}
catch(ClassCastException e)
{
throw new ServletException("non-HTTP request or response");
}
service(request, response);
}
40
What is written inside the protected service method?
The protected service method checks the type of request, if request type is get, it
calls doGet method, if request type is post, it calls doPost method, so on. Let's see
the internal code:
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
String method = req.getMethod();
if(method.equals("GET"))
{
long lastModified = getLastModified(req);
if(lastModified == -1L)
{
doGet(req, resp);
}
....
//rest of the code
}
} 41
welcome-file-list in web.xml
The welcome-file-list element of web-app, is used to define a list of
welcome files. Its sub element is welcome-file that is used to define the
welcome file.
A welcome file is the file that is invoked automatically by the server, if you
don't specify any file name.
By default server looks for the welcome file in following order:
welcome-file-list in web.xml
index.html
index.htm
index.jsp
If none of these files are found, server renders 404 error.
If you have specified welcome-file in web.xml, and all the files index.html,
index.htm and index.jsp exists, priority goes to welcome-file.
If welcome-file-list entry doesn't exist in web.xml file, priority goes to
index.html file then index.htm and at last index.jsp file.
42
Web.xml
<web-app>
....
<welcome-file-list>
<welcome-file>home.html</welcome-file>
<welcome-file>default.html</welcome-file>
</welcome-file-list>
</web-app>
43
load on startup in web.xml
The load-on-startup element of web-app loads the servlet at the time of
deployment or server start if value is positive. It is also known as pre
initialization of servlet.
You can pass positive and negative value for the servlet.
<servlet>
<servlet-name>servlet1</servlet-name>
<servlet-class>com.javatpoint.FirstServlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet>
<servlet-name>servlet2</servlet-name>
<servlet-class>com.javatpoint.SecondServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
...
</web-app>
There are defined 2 servlets, both servlets will be loaded at the time of project deployment or
server start. But, servlet1 will be loaded first then servlet2
Passing negative value
If you pass the negative value, servlet will be loaded at request time, at first request. 45
ServletRequest Interface
An object of ServletRequest is used to provide the client request information to a
servlet such as content type, content length, parameter names and values, header
informations, attributes etc.
Methods of ServletRequest interface
46
Example of ServletRequest to display the name of the user
47
Server
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class DemoServ extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
pw.close();
}}
48
RequestDispatcher in Servlet
The RequestDispatcher interface provides the facility of dispatching the request to
another resource it may be html, servlet or jsp. This interface can also be used to
include the content of another resource also. It is one of the way of servlet
collaboration.
49
As you see in the above figure, response of
second servlet is sent to the client. Response of
the first servlet is not displayed to the user.
50
As you can see in the above figure, response of second
servlet is included in the response of the first servlet
that is being sent to the client.
51
52
Example of RequestDispatcher interface
53
54
55
Login.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
String p=request.getParameter("userPass");
if(p.equals("servlet"){
RequestDispatcher rd=request.getRequestDispatcher("servlet2");
rd.forward(request, response);
}
else{
out.print("Sorry UserName or Password Error!");
RequestDispatcher rd=request.getRequestDispatcher("/index.html");
rd.include(request, response);
}
}
} 56
WelcomeServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
}
}
57
web.xml
<web-app>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list> 58
</web-app>
Session Tracking in Servlets
Session simply means a particular interval of time.
Session Tracking is a way to maintain state (data) of an user. It is also known as session
management in servlet.
Http protocol is a stateless so we need to maintain state using session tracking techniques.
Each time user requests to the server, server treats the request as the new request. So we need
to maintain the state of an user to recognize to particular user.
HTTP is stateless that means each request is considered as the new request. It is shown in the
figure given below:
59
Why use Session Tracking?
To recognize the user It is used to recognize the particular
user.
60
Cookies in Servlet
61
How Cookie works
By default, each request is considered as a new request. In cookies
technique, we add cookie with response from the servlet. So cookie is
stored in the cache of the browser. After that if request is sent by the user,
cookie is added with request by default. Thus, we recognize the user as the
old user.
62
Types of Cookie
There are 2 types of cookies in servlets.
Non-persistent cookie
Persistent cookie
Non-persistent cookie
It is valid for single session only. It is removed each time
when user closes the browser.
Persistent cookie
It is valid for multiple session . It is not removed each time
when user closes the browser. It is removed only if user logout
or signout.
63
Advantage of Cookies
Simplest technique of maintaining the state.
Cookies are maintained at client side.
Disadvantage of Cookies
It will not work if cookie is disabled from the
browser.
Only textual information can be set in Cookie
object.
64
Cookie class
65
Other methods required for using Cookies
66
67
How to get Cookies?
68
Simple example of Servlet Cookies
In this example, we are storing the name of the user in the cookie object
and accessing it in another servlet. As we know well that session
corresponds to the particular user. So if you access it from too many
browsers with different values, you will get the different value.
69
index.html
<form action="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
70
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
out.close();
}catch(Exception e){System.out.println(e);}
}
}
71
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());
out.close();
}catch(Exception e){System.out.println(e);}
}
72
}
Web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
73
</web-app>
2) Hidden Form Field
In case of Hidden Form Field a hidden (invisible) textfield is used for
maintaining the state of an user.
In such case, we store the information in the hidden field and get it from
another servlet. This approach is better if we have to submit form in all the
pages and we don't want to depend on the browser.
Here, uname is the hidden field name and Vimal Jaiswal is the hidden field
value.
74
75
Example of using Hidden Form Field
In this example, we are storing the name of the user in a
hidden textfield and getting that value from another servlet.
76
3)URL Rewriting
77
78
79
4) HttpSession interface
In such case, container creates a session id for each user.The container uses this id
to identify the particular user.An object of HttpSession can be used to perform two
tasks:
1) bind objects
2)view and manipulate information about a session, such as the session identifier,
creation time, and last accessed time.
80
81
Example of using HttpSession
In this example, we are setting the attribute in the session scope in one servlet and
getting that value from the session scope in another servlet. To set the attribute in
the session scope, we have used the setAttribute() method of HttpSession interface
and to get the attribute, we have used the getAttribute method.
82
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
HttpSession session=request.getSession();
session.setAttribute("uname",n);
out.print("<a href='servlet2'>visit</a>");
out.close();
}catch(Exception e){System.out.println(e);}
}
83
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session=request.getSession(false);
String n=(String)session.getAttribute("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){System.out.println(e);}
}
} 84
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
85
Database connectivity from the servlet
import java.io.*;
import java.util.*;
import javax.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n = request.getParameter("userName");
String p = request.getParameter("password");
String e = request.getParameter("email");
String c = request.getParameter("language");
88
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/servlet", "root", "mukesh");
PreparedStatement ps = con
.prepareStatement("insert into USERDETAILS values(?,?,?,?)");
ps.setString(1, n);
ps.setString(2, p);
ps.setString(3, e);
ps.setString(4, c);
int i = ps.executeUpdate();
if (i > 0)
out.print("You are successfully registered...");
out.close();
}
89
}
Servlet Program
Index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="AddServlet" method="get" align="center">
Enter First Number:<input type="text" name="num1" align="center">
Enter Second Number:<input type="text" name="num2" algin="center">
<input type="submit" value="Add" align="center">
</form>
</body>
</html>
90
AddServlet.java
package com.java1; IOException {
import java.io.PrintWriter; PrintWriter pw = response.getWriter();
import java.io.IOException; int i = Integer.parseInt(request.getParameter("num1"));
import jakarta.servlet.RequestDispatcher; int j = Integer.parseInt(request.getParameter("num2"));
import jakarta.servlet.ServletException; int k = i + j;
import jakarta.servlet.annotation.WebServlet; pw.println("result = "+k);
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet; }
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; }
import jakarta.servlet.http.HttpSession;
91
RequestDispatcher
RequestDispatcher is an interface that allows servlets to
forward or include requests and responses between
different servlets or web resources within the same web
application.
The RequestDispatcher interface is part of the Java
Servlet API, which provides a way for servlets to handle
HTTP requests and generate dynamic web content.
The RequestDispatcher is typically used when a servlet
needs to transfer control to another servlet or resource
within the same web application, such as forwarding a
request to another servlet to generate the response or
including the response of another servlet within the
current response. 92
RequestDispatcher
There are two main methods provided by the RequestDispatcher
interface:
forward(ServletRequest request, ServletResponse response): This
method forwards the request and response objects to another
servlet or resource, allowing the subsequent servlet or resource to
generate the response. The original request and response objects
are no longer available to the calling servlet after the forward is
performed.
include(ServletRequest request, ServletResponse response): This
method includes the response of another servlet or resource within
the current response. The calling servlet retains control and
continues processing after the included response is merged with its
own response.
93
As you see in the above figure, response of
second servlet is sent to the client. Response of
the first servlet is not displayed to the user.
94
As you can see in the above figure, response of second
servlet is included in the response of the first servlet
that is being sent to the client.
95
Request Dispatacher
AddServlet.java public AddServlet() {
// TODO Auto-generated constructor stub
package com.java1; }
import java.io.PrintWriter; protected void doGet(HttpServletRequest request,
import java.io.IOException; HttpServletResponse response) throws
import jakarta.servlet.RequestDispatcher; ServletException, IOException {
import jakarta.servlet.ServletException; PrintWriter pw = response.getWriter();
import jakarta.servlet.annotation.WebServlet; int i =
Integer.parseInt(request.getParameter("num1"));
import jakarta.servlet.http.Cookie;
int j =
import jakarta.servlet.http.HttpServlet; Integer.parseInt(request.getParameter("num2"));
import jakarta.servlet.http.HttpServletRequest; int k = i + j;
import jakarta.servlet.http.HttpServletResponse; pw.println("result = "+k);
import jakarta.servlet.http.HttpSession; request.setAttribute("k",k);
RequestDispatcher rd =
@WebServlet("/AddServlet") request.getRequestDispatcher("/Square");
public class AddServlet extends HttpServlet { rd.forward(request, response);
private static final long
serialVersionUID = 1L; }
96
Request Dispatacher
Square.java public class Square extends HttpServlet {
package com.java1; private static final long
import java.io.PrintWriter; serialVersionUID = 1L;
import java.io.IOException; protected void doGet(HttpServletRequest
import jakarta.servlet.ServletException; request, HttpServletResponse response)
throws ServletException, IOException {
import
jakarta.servlet.annotation.WebServlet; PrintWriter pw = response.getWriter();
import jakarta.servlet.http.Cookie; int k = (int) request.getAttribute("k");
import jakarta.servlet.http.HttpServlet; k = k * k;
import pw.println("result = "+k);
jakarta.servlet.http.HttpServletRequest; }
import
jakarta.servlet.http.HttpServletResponse; }
import jakarta.servlet.http.HttpSession;
@WebServlet("/Square")
97
Send Redirect
@WebServlet("/AddServlet") }
public class AddServlet extends HttpServlet {
private static final long
serialVersionUID = 1L;
99
SendRedirect
Square.java public class Square extends HttpServlet {
package com.java1; private static final long
import java.io.PrintWriter; serialVersionUID = 1L;
import java.io.IOException; protected void doGet(HttpServletRequest
import jakarta.servlet.ServletException; request, HttpServletResponse response)
throws ServletException, IOException {
import
jakarta.servlet.annotation.WebServlet; PrintWriter pw = response.getWriter();
import jakarta.servlet.http.Cookie; int k = (int) request.getAttribute("k");
import jakarta.servlet.http.HttpServlet; int k =
Integer.parseInt(request.getParameter("k"));
import
jakarta.servlet.http.HttpServletRequest; k = k * k;
import pw.println("result = "+k);
jakarta.servlet.http.HttpServletResponse; }
import jakarta.servlet.http.HttpSession;
@WebServlet("/Square") }
100
Session Management
AddServlet.java
/** * Default constructor. */
package com.java1; public AddServlet() {
import java.io.PrintWriter; // TODO Auto-generated constructor
stub
import java.io.IOException;
}
import jakarta.servlet.RequestDispatcher;
protected void doGet(HttpServletRequest
import jakarta.servlet.ServletException;
request, HttpServletResponse response)
import throws ServletException, IOException {
jakarta.servlet.annotation.WebServlet;
PrintWriter pw = response.getWriter();
import jakarta.servlet.http.Cookie;
int i =
import jakarta.servlet.http.HttpServlet; Integer.parseInt(request.getParameter("num
import 1"));
jakarta.servlet.http.HttpServletRequest; int j =
import Integer.parseInt(request.getParameter("num
jakarta.servlet.http.HttpServletResponse; 2"));
import jakarta.servlet.http.HttpSession; int k = i + j;
HttpSession session = request.getSession();
@WebServlet("/AddServlet") session.setAttribute("k", k);
public class AddServlet extends HttpServlet response.sendRedirect("Square");
{ 101
private static final long }
Session Management
Square.java private static final long
package com.java1; serialVersionUID = 1L;
import java.io.PrintWriter; protected void
import java.io.IOException; doGet(HttpServletRequest request,
HttpServletResponse response) throws
import jakarta.servlet.ServletException; ServletException, IOException {
import PrintWriter pw = response.getWriter();
jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
HttpSession session =
import jakarta.servlet.http.HttpServlet; request.getSession();
import int k = (int) session.getAttribute("k");
jakarta.servlet.http.HttpServletRequest;
k = k * k;
import
jakarta.servlet.http.HttpServletRespons pw.println("result = "+k);
e; }
import jakarta.servlet.http.HttpSession;
@WebServlet("/Square") } 102
public class Square extends
Cookies
Cookies are the textual information that is stored in key-value pair
format to the client’s browser during multiple requests. It is one of
the state management techniques in session tracking.
Basically, the server treats every client request as a new one so to
avoid this situation cookies are used. When the client generates a
request, the server gives the response with cookies having an id
which are then stored in the client’s browser.
Thus if the client generates a second request, a cookie with the
matched id is also sent to the server. The server will fetch the cookie
id, if found it will treat it as an old request otherwise the request is
considered new.
For example when you log in to a website and select "Remember
Me" or "Keep me signed in" option. The website may use a cookie to
remember your login information, so that you don't have to enter it
every time you visit the site.
103
104
Cookie
AddServlet.java }
protected void doGet(HttpServletRequest request,
package com.java1; HttpServletResponse response) throws ServletException,
import java.io.PrintWriter; IOException {
import java.io.IOException; PrintWriter pw = response.getWriter();
import jakarta.servlet.RequestDispatcher; int i = Integer.parseInt(request.getParameter("num1"));
import jakarta.servlet.ServletException; int j = Integer.parseInt(request.getParameter("num2"));
import jakarta.servlet.annotation.WebServlet; int k = i + j;
import jakarta.servlet.http.Cookie; pw.println("result = "+k);
import jakarta.servlet.http.HttpServlet; Cookie cookie = new Cookie("k",k + "");
import jakarta.servlet.http.HttpServletRequest; response.addCookie(cookie);
import jakarta.servlet.http.HttpServletResponse; response.sendRedirect("Square");
import jakarta.servlet.http.HttpSession;
}
@WebServlet("/AddServlet")
public class AddServlet extends HttpServlet {
private static final long serialVersionUID =
1L;
105
Cookie
Square.java serialVersionUID = 1L;
package com.java1; protected void doGet(HttpServletRequest
import java.io.PrintWriter; request, HttpServletResponse response)
import java.io.IOException; throws ServletException, IOException {
import jakarta.servlet.ServletException; PrintWriter pw = response.getWriter();
import //int k = 0;
jakarta.servlet.annotation.WebServlet; //Cookie cookies[] = request.getCookies();
import jakarta.servlet.http.Cookie; //for(Cookie c : cookies) {
import jakarta.servlet.http.HttpServlet; //if(c.getName().equals("k"))
import //k = Integer.parseInt(c.getValue());
jakarta.servlet.http.HttpServletRequest; //}
import //k = k * k;
jakarta.servlet.http.HttpServletResponse; pw.println("result = "+k);
import jakarta.servlet.http.HttpSession; }
@WebServlet("/Square")
public class Square extends HttpServlet { }
private static final long
106