Unit 1 Servlet
Unit 1 Servlet
TOPICS TO BE DISCUSSED
WEB APPLICATION
WAR FILE
SERVERS
PORTS
SERVERSIDE PROGRAMMING
WEB SERVER/APPLICATION SERVER
CGI SCRIPT
SERVLET
CGI vs SERVLET
SERVLET CONTAINER
SERVLET PACKAGE
SERVLET LIFE CYCLE
FIRST SERVLET
2 26/10/2024
3 26/10/2024
War File
4 26/10/2024
Servers
A server is a computer that responds to requests from a
client
Typical requests: provide a web page, upload or download a file,
send email
A server is also the software that responds to these
requests; a client could be the browser or other software
making these requests
Typically, your little computer is the client, and someone
else’s big computer is the server
However, any computer can be a server
It is not unusual to have server software and client software running
on the same computer
26/10/2024
5
Apache
Apache is a very popular server
66% of the web sites on the Internet use
Apache
Apache is:
Full-featured and extensible
Efficient
Robust
Secure (at least, more secure than other
servers)
Up to date with current standards
Open source
Free
26/10/2024
6
Tomcat
Tomcat is the Servlet Engine than handles
servlet requests for Apache
Tomcat is a “helper application” for Apache
It’s best to think of Tomcat as a “servlet container”
Apache can handle many types of web services
Apache can be installed without Tomcat
Tomcat can be installed without Apache
It’s easier to install Tomcat standalone than as
part of Apache
By itself, Tomcat can handle web pages, servlets, and
JSP
Apache and Tomcat are open source (and
therefore free)
26/10/2024
7
Ports
A port is a connection between a server and a client
Ports are identified by positive integers
A port is a software notion, not a hardware notion, so there may be
very many of them
A service is associated with a specific port
Typical port numbers:
21—FTP, File Transfer Protocol
3306 —SQL SERVER
25—SMTP, Simple Mail Transfer Protocol
53—DNS, Domain Name Service
80—HTTP, Hypertext Transfer Protocol
8080—HTTP (used for testing HTTP)
These are the
ports of most
interest to us
26/10/2024
8
Why Server Side Programming?
Though it is technically feasible to implement almost any business logic
using client side programs, logically or functionally it carries no ground when
it comes to enterprise applications (e.g. banking, air ticketing, e-shopping
etc.).
To further explain, going by the client side programming logic; a
bank having 10,000 customers would mean that each customer should have a
copy of the program(s) in his or her PC which translates to 10,000 programs!
In addition, there are issues like security, resource pooling, concurrent access
and manipulations to the database which simply cannot be handled by client
side programs. The answer to most of the issues cited above is ?
Server Side Programming?.
9 26/10/2024
Server Side Programming
10 26/10/2024
Advantages of Server Side Programs
I. All programs reside in one machine called the
Server. Any number of remote machines (called
clients) can access the server programs.
II. New functionalities to existing programs can be
added at the server side which the clients? can
advantage without having to change anything
from their side.
III. Migrating to newer versions, architectures,
design patterns, adding patches, switching to
new databases can be done at the server side
without having to bother about clients
hardware or software capabilities.
11 26/10/2024
Advantages of Server Side
Programs Cont..
I. Issues relating to enterprise applications
like resource management, concurrency,
session management, security and
performance are managed by service side
applications.
II. They are portable and possess the
capability to generate dynamic and user-
based content (e.g. displaying transaction
information of credit card or debit card
depending on user?s choice).
12 26/10/2024
Advantages of Server Side
Programs Cont …
The server-side extensions are nothing but the technologies that
are used to create dynamic Web pages. Actually, to provide the
facility of dynamic Web pages, Web pages need a container or
Web server. To meet this requirement, independent Web server
providers offer some proprietary solutions in the form
of APIs(Application Programming Interface).
These APIs allow us to build programs that can run with a Web
server. In this case , Java Servlet is also one of the component
APIs of Java Platform Enterprise Edition which sets standards
for creating dynamic Web applications in Java
13 26/10/2024
Server: Web vs. Application
14 26/10/2024
Web Server
Web server contains only web or servlet container. It can be
used for servlet, jsp, struts, jsf etc. It can't be used for EJB.
It is a computer where the web content can be stored. In
general web server can be used to host the web sites but
there also used some other web servers also such as FTP,
email, storage, gaming etc.
Examples of Web Servers are:
Apache Tomcat and Resin.
15 26/10/2024
Web Server
A web server is the combination of computer and the
program installed on it. Web server interacts with the client
through a web browser. It delivers the web pages to the
client and to an application by using the web browser and
the HTTP protocols respectively.
We can also define the web server as the package of large
number of programs installed on a computer connected to
Internet or intranet for downloading the requested files
using File Transfer Protocol, serving e-mail and building
and publishing web pages.
16 26/10/2024
Application Server
17 26/10/2024
The Example of Application Servers are:
18 26/10/2024
CGI Scripts
CGI stands for “Common Gateway Interface”
26/10/2024
19
CGI Communication (traditional
approach)
Web browser
3. execute CGI program
and wait for CGI to terminate
5
1. request
CGI terminated
Request
Servlet
21 26/10/2024
What is Servlet cont …
22 26/10/2024
Example use of Servlet
Processing data POST over HTTPs using HTML form as purchase order or
credit card data
Allowing collaborative between people such as on-line conferencing
Many servlet can chain together among Web servers to reduce load on one
Web server.
23 26/10/2024
Why Use Servlets ?
One of the reasons that Java became
popular is Applets.
but there are problems with Applets
Browser compatibility
Download bandwidth
Server-side Java
the code is executed on the server side not
the client side
a dynamically loaded module that services
requests from a Web server
24 26/10/2024
Benefits
25 26/10/2024
Why Use Servlet
26 26/10/2024
Why use Servlet Cont …
27 26/10/2024
Servlets
A servlet is like an applet, but on the server side
26/10/2024
28
Servlet Communication
31 26/10/2024
32 26/10/2024
How Servlet Works
33 26/10/2024
Life Cycle of a Servlet
The web container maintains the life cycle
of a servlet instance. Let's see the life cycle
of the servlet:
1. Servlet class is loaded.
2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.
34 26/10/2024
Life cycle of Servlet
35 26/10/2024
Servlet Life Cycle
The life cycle of the servlet is
controlled by the servlet container.
The servlet container is responsible
for doing following task
When the first request is made for
servlet the containet loads the servlet
class and initiates it.
Then make an instance of servlet
class.
Initializes the servlet class by calling
init() method.
Call the service method passes the
request response object to the service
method.
If container need to remove the
servlet then call the destroy() method
to finalize the servlet.
36 26/10/2024
servlet
37 26/10/2024
Life Cycle of a Servlet (Servlet Life Cycle)
Cont ….
38 26/10/2024
39 26/10/2024
1) Servlet class is loaded
40 26/10/2024
2) Servlet instance is created
41 26/10/2024
3) init method is invoked
42 26/10/2024
4) service method is invoked
The web container calls the service method each time when
request for the servlet is received. If servlet is not initialized, it
follows the first three steps as described above then calls the
service method. If servlet is initialized, it calls the service
method. Notice that servlet is initialized only once.
The syntax of the service method of the Servlet interface is given
below:
public void service(ServletRequest request, ServletResponse res
ponse) throws ServletException, IOException
43 26/10/2024
5) destroy method is invoked
44 26/10/2024
Servlet Container
45 26/10/2024
46 26/10/2024
Servlet Container Cont ....
47 26/10/2024
Servlet Container
48 26/10/2024
Services provided by the Servlet
container :
Network Services : Loads a Servlet class. The loading may be from a
local file system, a remote file system or other network services. The
Servlet container provides the network services over which the request
and response are sent.
Decode and Encode MIME based messages : Provides the service of
decoding and encoding MIME-based messages.
Manage Servlet container : Manages the lifecycle of a Servlet.
Resource management : Manages the static and dynamic resource,
such as HTML files, Servlets and JSP pages.
Security Service : Handles authorization and authentication of
resource access.
Session Management : Maintains a session by appending a session
ID to the URL path
49 26/10/2024
The Container does the following thing-
When the request comes at first for the servlet, then it load
the servlet, initialize it by calling servlet init() method.
Makes a thread of the requested servlet
Makes an instance of ServletRequest and ServletResponse
of javax.servlet.*; package
Passes the ServletRequest and ServletResponse reference
variables to the servlet service method
Take the ServletResponse object from the servlet and
passes to the web server
And finally destroy the reference variables and destroy the
servlet when the is shut down.
50 26/10/2024
Servlet API ( Application Programming
Interface)
51 26/10/2024
Servlets API’s:
Servlets are build from two packages:
javax.servlet(Basic)
package contains many interfaces and classes that
are used by the servlet or web container. These are
not specific to any protocol.
javax.servlet.http(Advance)
package contains interfaces and classes that are
responsible for http requests only.
52 26/10/2024
53 26/10/2024
PACKAGE SUMMARY
java.io package povides the input and output
facilities, this package is a standard package of core
java platform. It is used for PrintWriter class
javax.servlet :- ServletException class is contained
by this package. Every servlet throws the servlet
exception therefore it is necessary to include this
package in your program.
javax.servlet.http :- HttpServletRequest and
HttpServletResponse interfaces are contained by
this package. The HttpServletRequest and
HttpServletResponse objects created by the servlet
container which is passes through the service
method doGet(), doPost(), etc. to get servlet request
and send servlet response to the client respectively.
54 26/10/2024
Http Servlet -
HttpServlet is HTTP (Hyper Text Transfer Protocol )
specific servlet. It provides an abstract class
HttpServlet for the developers for extend to create
there own HTTP specific servlets.
The sub class of HttpServlet must overwrite at least
one method given below-
doGet()
doPost()
doTrace()
doDelete()
init()
destroy()
getServiceInfo()
55 26/10/2024
Difference B/W Generic and HTTP
servlet Package
Generic Servlet Http Servlet
GenericServlet belongs HttpServlet belongs to
to javax.servlet javax.servlet.http
package while package.
GenericServlet is an HTTPServlet is an
abstract class which
abstract class which
extends GenericServlet
extends Object and and implements
implements Servlet, java.io.Serializable.
ServletConfig and HttpServlet must override
java.io.Serializable at least one method of
interfaces doGet(), doPost(),doPut(),
. To write a doDelete(), init(),
GenericServlet you destroy(), getServletInfo().
HTTPServlet is a protocol
need abstract service()
to be overridden dependent servlet.
)GenericServlet is a
56
protocol-independent 26/10/2024
servlet
Javax.servlet package
57 26/10/2024
58 26/10/2024
javax.servlet.
59 26/10/2024
Servlet - This interface defines method for all servlets interfac
ServletConfig - This interface is used by servlet container to pass the
e
parameter to servlet. This interface is used for individual servlet and unknown
to the other servlets
ServletContext - This interface contains a set of methods, which is used to
communicate with the servlet container and other servlets servlets within an
application
ServletRequest - This interface provides a client request information to the
servlet
ServletResponse - This interface provides a servlet response information to
the client, it assists the servlet to send the response information to the client.
RequestDispatcher - This interface accepts the request from the client sends
it to the other application resources.
Filter - It performs the filter task on either request or response to the resources
60 26/10/2024
Interface cont
…. for a resource.
FilterChain - This view a chain of filter request
FilterConfig - It used by the servlet container to pass the information
during initialization to the of the filter
ServletContextListener - This interface receive a notification when a
ServletContext of a web application is initialaised
ServletRequestListener - This interface can be implemented if
developer wants to notify when any request out of the scope of web
application is coming
ServletContextAttributeListener - This interface receive a notification
when a change is made in the ServletContext
ServletRequestAttributeListener - This interface receive a notification
when changes is made in request attribute.
SingleThreadModel - This interface is deprecated after the java servlet
2.4.
61 26/10/2024
Classes
GenericServlet - This class defines a generic, protocol independent servlet.
ServletContextAttributeEvent - This is a event class for, when the attribute of
an application changes this class receives a nification.
ServletContextEvent - This class receive a notifications when the
ServletContext of an application is changes.
ServletInputStream - This provides a servlet input stream for reading binary
data from the client.
ServletOutputStream - This class provides an output steam for sending binary
data to the client.
ServletRequestWrapper - This class provides the implementation of
ServletRequest interface, the developers can subclass this for their own specific
use
ServletResponseWrapper - This class provides the implementation of
ServletResponse interface, the developers can subclass this for their own specific
use
ServletRequestAttributeEvent - This is a event class it receive a notification
when any change made in the request attribute of the application
ServletRequestEvent - This event class indicates the events of the servlet class
62 26/10/2024
javax.servlet.http.
63 26/10/2024
Interfaces
HttpServletRequest - This interface extends the ServletRequest interface
for provide http specific servlet request
HttpServletResponse - This interface extends the ServletResponse interface
for provide http specific servlet response
HttpSession - It provides a way for identifying a user on the website
HttpSessionActivationListener - This interface notify when when session is
Activated
HttpSessionAttributeListener - This interface can be implemented in order
to get notification when attribute of the session is changed
HttpSessionBindingListener - This interface can be implemented in order
to get notification when object is bound or unbound to the session
HttpSessionContext - This interface is deprecated in servlet 2.1 for security
resion
HttpSessionListener - When developer want to notify the session activation
or de-activation, can implement this interface
64 26/10/2024
Classes
Cookie - It creates a cookie sent by a servlet to the web browser, which
browser saves and latter return for further communication
HttpServlet - This is an abstract class, to create a Http specific servlet
you need to extend this class
HttpServletRequestWrapper -This class implements the
HttpServletRequest interface, the developer can also subclass this for
their specific use
HttpServletResponseWrapper - This class implements the
HttpServletResponse interface, the developer can also subclass this for
their specific use
HttpSessionBindingEvent - This is an events class, it is activated
when session is bound and unbound
HttpSessionEvent - This event class generates a notification for
changes to the session within a web application
HttpUtils - This class is deprecated in servlet 2.3 API
65 26/10/2024
Servlet Interface
66 26/10/2024
Methods of Servlet interface
There are 5 methods in Servlet interface. The init,
service and destroy are the life cycle methods of
servlet. These are invoked by the web container.
67 26/10/2024
ServletRequest Interface
68 26/10/2024
69 26/10/2024
Index.html
<body>
<form action ="first">
<p> Name<input type="text"
name="username"></p>
<p> <input type="submit"
value="first"></p>
</form>
</body>
70 26/10/2024
SERVLET CODE
out.println("<h1>Welcome to my first
servlet</h1>");
String user =
request.getParameter("username");
out.println("<h2> Welcome
"+user+"</h2>");
java.util.Date date = new java.util.Date();
out.println("<h2>"+"Current Date &
Time: " +date.toString()+"</h2>");
71 26/10/2024
QUESTION:
DISPLAY DATAE AND TIME IN THIS FORMAT
Display Current Date & Time
Mon 2010.06.21 at 10:06:44 PM
GMT+04:00
72 26/10/2024
Html code
<form action="Counter">
<h1> <input type="submit"
value="submit"></h1>
</form>
73 26/10/2024
HIT COUNTER
Servlet interface
import java.io.*; provides common behavior to all
import javax.servlet.*; the servlets.Servlet interface
import javax.servlet.http.*; defines methods that all servlets
must implement.
public class Counter extends HttpServlet{
int counter = 0;
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
counter++;
pw.println(“TOTAL COUNT= " + counter);
}
}
74 26/10/2024
RequestDispatcher in Servlet
75 26/10/2024
Methods of RequestDispatcher
interface
The RequestDispatcher interface provides two methods. They are:
public void forward(ServletRequest request,ServletResponse
response)throws ServletException,java.io.IOException:
Forwards a request from a servlet to another resource (servlet, JSP
file, or HTML file) on the server.
public void include(ServletRequest request,ServletResponse
response)throws ServletException,java.io.IOException:Includes
the content of a resource (servlet, JSP page, or HTML file) in the
response.
76 26/10/2024
IN GIVEN figure, response of second servlet is
sent to the client. Response of the first servlet is
not displayed to the user.
77 26/10/2024
IN GIVEN figure, response of second servlet is included in
the response of the first servlet that is being sent to the
client.
78 26/10/2024
Html code
<body>
<form action="Login" method="post">
Name:<input type="text"
name="userName"/><br/>
Password:<input type="password"
name="userPass"/><br/>
<input type="submit" value="login"/>
</form>
</body>
79 26/10/2024
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Login extends HttpServlet {
Login.java
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String username=request.getParameter("userName");
String paas=request.getParameter("userPass");
if(paas.equals("sharma"))
{
RequestDispatcher rd=request.getRequestDispatcher("welcomeservlet");
rd.forward(request, response);
}
else{
out.print("Sorry UserName or Password Error!");
RequestDispatcher rd=request.getRequestDispatcher("/index.html");
rd.include(request, response);
80 26/10/2024
} } }
welcomeservlet
out.println("<h1>welcome to servlet
</h1>");
//String user =
request.getParameter("username");
// out.println("<h2> Welcome
"+user+"</h2>");
81 26/10/2024
SendRedirect in servlet
82 26/10/2024
HTML CODE
<form action=" SendServlet ">
<h1> <input type="submit"
value="submit"></h1>
</form>
83 26/10/2024
sendRedirect()
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.sendRedirect("https://www.amazon.in/");
pw.close();
}}
84 26/10/2024
HTML CODE
<form action=“GoogleSearch">
<input type="text" name="name">
<input type="submit" value="Google Sear
ch">
</form>
85 26/10/2024
sendRedirect()
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
String name=request.getParameter("name");
response.sendRedirect("https://www.google.co.in/
#q="+name);
}
}
86 26/10/2024
FORWARD() SENDREDIRECT()
The request is shared by the target New request is created for the
resource. destination resource.
Only one call is consumed in this Two request and response calls are
method. consumed.
It is declared in It is declared in
RequestDispatcher interface. HttpServletResponse.
87 26/10/2024
FORWARD() SENDREDIRECT()
Signature :
forward(ServletRequest Signature:
request, ServletResponse void sendRedirect(String url)
response)
88 26/10/2024
Some more points to notice of forward vs
sendRedirect.
89 26/10/2024
Which one is preferred?
</form>
91 26/10/2024
Reading Parameter values
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
92 26/10/2024
Servlet types
There are mainly two types of servlets -
Generic Servlet - Generic
servlet is protocol
independent servlet. It
implements the Servlet and
ServletConfig interface. It
may be directly extended by
the servlet. Writing a servlet
in in GenericServlet is very
easy. It has only init() and
destroy() method of
ServletConfig interface in its
life cycle. It also implements
the log method of
ServletContext interfac
93 26/10/2024
ServletConfig Interface
94 26/10/2024
Advantage of ServletConfig
95 26/10/2024
How to get the object of ServletConfig
96 26/10/2024
ServletContext Interface in Servlet
97 26/10/2024
Commonly used methods of ServletContext
interface
98 26/10/2024
How to get the object of ServletContext
interface
getServletContext() method of
ServletConfig interface returns the object of
ServletContext.
getServletContext() method of
GenericServlet class returns the object of
ServletContext.
Syntax of getServletContext() method
public ServletContext getServletContext()
99 26/10/2024
Advantages of ServletContext
10 26/10/2024
0
10 26/10/2024
1
HTML FILE
<form action="MyServlet">
<input type="submit"
value="submit">
</form>
10 26/10/2024
2
SERVLET FILE
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html;charset=UTF-8");
out.println(sc.getInitParameter("dname"));
}}
10 26/10/2024
3
Web.xml
<context-param>
<param-name>dname</param-name>
<param-
value>sun.jdbc.odbc.JdbcOdbcDriver</
param-value>
</context-param>
10 26/10/2024
4
ServletConfig
10 26/10/2024
5
ServletContext
ServletContext available in javax.servlet.*; package
ServletContext object is global to entire web application
Object of ServletContext will be created at the time of web
application deployment
Scope: As long as web application is executing, ServletContext object will be
available, and it will be destroyed once the application is removed from the
server.
ServletContext object will be available even before giving the first request
In web.xml – <context-param> tag will be appear under <web-app> tag
So finally…….
No. of web applications = That many number of ServletContext objects [ 1 per
web application ]
No. of servlet classes = That many number of ServletConfig objects
10 26/10/2024
6
Difference between ServletConfig and
ServletContext
10 26/10/2024
7
Attribute in Servlet
10 26/10/2024
8
Attribute in Servlet
10 26/10/2024
9
What we do with these attributes?
11 26/10/2024
0
Attribute specific methods of ServletRequest,
HttpSession and ServletContext interface
11 26/10/2024
1
HTML FILE
<form action="First">
<input type="submit"
value="submit">
</form>
11 26/10/2024
2
First.java to SET an Attribute
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
ServletContext sc = getServletContext();
sc.setAttribute("user","MCA"); //setting attribute on context scope
out.println("<a href='Second'>visit</a>");
}
}
11 26/10/2024
3
Second.java to GET An Attribute
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
11 26/10/2024
4
How servlet is used with each scope
of Object?
1.Request Attribute:
“This object attributes are accessible only within that same servlet request
object.”
We can set and get Request Attributes with an object.
You can do all the operations mentioned above with request object.
For example:
Request.setAttribute(“fruits”,FruitsObject);
Request.getAttribute(“fruits”)
11 26/10/2024
5
Session Tracking in Servlet
11 26/10/2024
6
Why need Session Tracking ?
Http protocol is stateless, to make stateful
between client and server we need Session
Tracking.
Session Tracking is useful for online shopping,
mailing application, E-Commerce application to
track the conversion.
Http protocol is stateless, that means each
request is considered as the new request. You
can see in below image
11 26/10/2024
7
Why use Session Tracking ?
To recognize the user It is used to recognize
the particular user.
Why Http is design as stateless
protocol ?
If Http is stateful protocol for multiple
requests given by client to web application
single connection will be used between
browser and web server across the multiple
requests. This may make clients to engage
connection with web server for long time
event though the connection are ideal. Due
to this the web server reach to maximum
11
connections even though most of its 26/10/2024
8
connection are idle. To overcome this
Session tracking methods:
User authorization
Hidden fields
URL rewriting
Cookies
Session tracking API
11 26/10/2024
9
SESSION TRACKING TECHNIQUES
12 26/10/2024
0
Multiple CheckBox Example
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CheckBox extends HttpServlet{
public void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException,
IOException{
String name;
String[] hobbies;
res.setContentType("text/html");
name= req.getParameter("name");
PrintWriter pw = res.getWriter();
hobbies= req.getParameterValues("hobbies");
if(hobbies!=null)
{
pw.println("<html><body bgcolor=#00fffff>");
pw.println("Hi I am <h4>"+name+".</h4><br>");
pw.println("My hobby/hobbies are:");
for(int i=0; i<hobbies.length; i++){
pw.println(hobbies[i]+",");
}
pw.println("</body></html>");
}
else
pw.println("<p><font color=red>not selected</font></p>");
}
12 } 26/10/2024
1
Deployment Descriptors
12 26/10/2024
3
cookie
Cookies are text files stored on the client computer and
they are kept for various information like name, a single
value, and optional attributes such as a comment, path
and domain qualifiers, a maximum age, and a version
number.
• or
A cookie is a small piece of information that is persisted
between the multiple client requests.
A cookie has a name, a single value, and optional
attributes such as a comment, path and domain
qualifiers, a maximum age, and a version number.
12 26/10/2024
4
How Cookie works
12 26/10/2024
5
Cookies in Servlet
12 26/10/2024
6
How Cookie works
12 26/10/2024
7
When use cookies ?
12 26/10/2024
8
Points to Remember
12 26/10/2024
9
Types of Cookie
There are 2 types of cookies in servlets.
1. Non-persistent cookie
2. 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.
13 26/10/2024
0
Advantage of Cookies
Simplest technique of maintaining the
state.
Cookie are maintained at client side so they
do not give any burden to server.
All server side technology and all web
server, application servers support cookies.
Presistent cookies can remember client
data during session and after session with
expiry time.
13 26/10/2024
1
Limitation of Cookies
13 26/10/2024
2
Session Cookies
request request
13 26/10/2024
3
Session Cookies
request request
13 26/10/2024
4
Session Cookies
request request
Cookie: id1
id2
Servlet
Servlet
id1
response response
id1
Web
browser 1 Session
Web server read/write
13 26/10/2024
5
Session Cookies
request request
Cookie: id2
id2
Servlet
Servlet
id2
response response
id1
Web
browser 2 Session
Web server read/write
13 26/10/2024
6
Create Cookies
13 26/10/2024
7
Add Cookies
13 26/10/2024
8
Read Cookies for browser
13 26/10/2024
9
HTML CODE
<form action="FirstServlet"
method="post">
Name:<input type="text"
name="userName"/> <br/>
<input type="submit" value="continue"/>
</form>
14 26/10/2024
0
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
String n=request.getParameter("userName");
out.print("Welcome "+n);
14
out.close(); 26/10/2024
1 } }
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());
out.close();
14 } } 26/10/2024
2
URL rewriting:
14 26/10/2024
3
How to get parameter value from url
in servlet?
14 26/10/2024
4
Advantages of URL rewriting:
14 26/10/2024
5
14 26/10/2024
6
HTML CODE
<form action="Servlet1">
Name <input type="text"
name="uname">
<input type="submit"
value="submit">
</form>
14 26/10/2024
7
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
String n=request.getParameter("uname");
out.print("Welcome "+n);
out.close();
}
}
14 26/10/2024
8
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
out.close();
}
}
14 26/10/2024
9
Hidden Form Field
15 26/10/2024
0
Hidden Form Field
15 26/10/2024
4
Hidden Form Field Limitations
More complex than URL Rewriting.
It is maintained at server side.
Extra form submission is required on each
pages.
Hidden form field can not store java object
as values. They only store text value
It Also increase network traffic because
hidden boxes data travels over the network
along with request and response.
Hidden boxes does not provides data
security because their data can be view
15
5
through view source option. 26/10/2024
HTML FILE
<form action="FirstServlet ">
Name:<input type="text"
name="userName"/>
<br/>
<input type="submit" value="continue"/>
</form>
15 26/10/2024
6
mport java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response){
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
out.print("<form action='servlet2' >");
out.print("<input type='hidden' name='uname' value='"+n+"'>");
out.print("<input type='submit' value='continue'>");
out.print("</form>");
out.close();
}
15 26/10/2024
7 }
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.close();
}catch(Exception e){System.out.println(e);}
}
}
15 26/10/2024
8
HttpSession interface
15 26/10/2024
9
16 26/10/2024
0
How to get the HttpSession
object
The HttpServletRequest interface provides
two methods to get the object of
HttpSession:
public HttpSession
getSession():Returns the current session
associated with this request, or if the
request does not have a session, creates
one.
public HttpSession getSession(boolean
create):Returns the current HttpSession
associated with this request or, if there is
no current session and create is true,
16 26/10/2024
1 returns a new session.
Commonly used methods of HttpSession interface
public String getId():Returns a string
containing the unique identifier value.
public long getCreationTime():Returns the
time when this session was created, measured in
milliseconds since midnight January 1, 1970 GMT.
public long getLastAccessedTime():Returns
the last time the client sent a request associated
with this session, as the number of milliseconds
since midnight January 1, 1970 GMT.
public void invalidate():Invalidates this session
then unbinds any objects bound to it.
16 26/10/2024
2
< form action="login">
User Name:<input type="text"
name="userName"/> <br/>
Password:<input
type="password"name="userPassword"/>
<br/> <input type="submit"
value="submit"/> </form>
16 26/10/2024
3
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet1 extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();
16 26/10/2024
4
String name = request.getParameter("userName");
String password = request.getParameter("userPassword");
pwriter.print("Hello "+name);
pwriter.print("Your Password is: "+password);
HttpSession session=request.getSession();
session.setAttribute("uname",name);
session.setAttribute("upass",password);
pwriter.print("<a href='welcome'>view details</a>");
pwriter.close();
}catch(Exception exp){
System.out.println(exp);
}
16 } 26/10/2024
5
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();
HttpSession session=request.getSession(false);
String myName=(String)session.getAttribute("uname");
String myPass=(String)session.getAttribute("upass");
pwriter.print("Name: "+myName+" Pass: "+myPass);
pwriter.close();
}catch(Exception exp){ System.out.println(exp);
}
16 26/10/2024
6 }