SlideShare ist ein Scribd-Unternehmen logo
1 von 83
Java Servlet
Prepared By
Yogaraja C A
Ramco Institute of Technology
Definition
 Servlet technology is used to create a web application
(resides at server side and generates a dynamic web
page).
 Before Servlet, CGI (Common Gateway Interface)
scripting language was common as a server-side
programming language.
 Servlet is an interface that must be implemented for
creating any Servlet.
 Servlet is a class that extends the capabilities of the
servers and responds to the incoming requests. It can
respond to any requests.
CGI (Common Gateway Interface)
 CGI technology enables the web server to call an
external program and pass HTTP request information to
the external program to process the request. For each
request, it starts a new process.
Disadvantages of CGI
 If the number of clients increases, it takes more
time for sending the response.
 For each request, it starts a process, and the web
server is limited to start processes.
 It uses platform dependent language e.g. C, C++,
perl.
Advantages of Servlet
The web container creates threads for handling the multiple
requests to the Servlet. Threads have many benefits over the
Processes such as they share a common memory area,
lightweight, cost of communication between the threads are
low.
 Better performance: because it creates a thread for
each request, not process.
 Portability: because it uses Java language.
 Robust: JVM manages Servlets, so we don't need to
worry about the memory leak, garbage collection, etc.
 Secure: because it uses java language.
Static vs Dynamic website
Static Website Dynamic Website
Prebuilt content is same every time the page
is loaded.
Content is generated quickly and changes
regularly.
It uses the HTML code for developing a
website.
It uses the server side languages such as
PHP,SERVLET, JSP, and ASP.NET etc. for
developing a website.
It sends exactly the same response for every
request.
It may generate different HTML for each of
the request.
The content is only changed when someone
publishes and updates the file (sends it to the
web server).
The page contains "server-side" code which
allows the server to generate the unique
content when the page is loaded.
Flexibility is the main advantage of static
website.
Content Management System (CMS) is the
main advantage of dynamic website.
Servlet Container
 It provides the runtime environment for JavaEE (j2ee)
applications. The client/user can request only a static WebPages
from the server. If the user wants to read the web pages as per
input then the servlet container is used in java.
 The servlet container is the part of web server which can be run
in a separate process. We can classify the servlet container
states in three types:
Servlet Container States
The servlet container is the part of web server which can be run in a
separate process. We can classify the servlet container states in three
types:
 Standalone: It is typical Java-based servers in which the servlet
container and the web servers are the integral part of a single
program. For example:- Tomcat running by itself
 In-process: It is separated from the web server, because a different
program runs within the address space of the main server as a
plug-in. For example:- Tomcat running inside the JBoss.
 Out-of-process: The web server and servlet container are different
programs which are run in a different process. For performing the
communications between them, web server uses the plug-in
provided by the servlet container.
Servlets - Life Cycle/Architecture
A servlet life cycle can be defined as the entire process
from its creation till the destruction.
 The servlet is initialized by calling the init() method.
 The servlet calls service() method to process a client's
request.
 The servlet is terminated by calling the destroy()
method.
 Finally, servlet is garbage collected by the garbage
collector of the JVM.
Steps to create a servlet
To create servlet using apache tomcat server, 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
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.
Create a servlet
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.
Compile the servlet
For compiling the Servlet, jar file is required to
be loaded. Different Servers provide different
jar files:
jar file Server
servlet-api.jar Apache Tomcat
weblogic.jar Weblogic
javaee.jar Glassfish
javaee.jar JBoss
Create the deployment descriptor (web.xml
file)
The deployment descriptor is an xml file, from
which Web Container gets the information about
the servlet 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
<web-app>
<servlet>
<servlet-name>ABC</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ABC</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
Web.xml Description
<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.
Servlet API
Servlet Interface
 Servlet interface provides common behavior to all the
servlets. Servlet interface defines methods that all
servlets must implement.
 Servlet interface needs to be implemented for creating
any servlet (either directly or indirectly).
 It provides 3 life cycle methods that are used
to initialize the servlet,
to service the requests, and
to destroy the servlet and
2 non-life cycle methods.
Methods of Servlet interface
Method Description
public void init(ServletConfig config)
initializes the servlet. It is the life cycle
method of servlet and invoked by the
web container only once.
public void service(ServletRequest
request,ServletResponse response)
provides response for the incoming
request. It is invoked at each request by
the web container.
public void destroy()
is invoked only once 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.
Servlet Example by implementing Servlet interface
public class First implements Servlet {
ServletConfig config=null;
public void init(ServletConfig config){
System.out.println("servlet is initialized"); }
public void service(ServletRequest req,ServletResponse res)
throws IOException,ServletException{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello simple servlet </b>");
out.print("</body></html>"); } }
GenericServlet class
GenericServlet class implements Servlet,
ServletConfig and Serializable interfaces. 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.
Methods of GenericServlet class
 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 void log(String msg) writes the given message in the servlet log file.
Servlet by inheriting the GenericServlet class
public class First extends GenericServlet{
public void service(ServletRequest req,ServletResponse res)
throws IOException,ServletException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello generic servlet</b>");
out.print("</body></html>");
}
}
HttpServlet class
The HttpServlet class extends the GenericServlet
class and implements Serializable interface.
It provides http specific methods such as doGet,
doPost, doHead, doTrace etc.
Methods of HttpServlet class
 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.
Methods of HttpServlet class
 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.
Servlet by inheriting the HttpServlet class
public class First extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
pw.println("<html><body>");
pw.println("Welcome to servlet");
pw.println("</body></html>");
pw.close();
}}
Working of Servlet
How Servlet works?
 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.
How web container handles the servlet request?
The web container is responsible to handle the request.
 maps the request with the servlet in the web.xml file.
 creates request and response objects for this request
 calls the service method on the thread
 The public service method internally calls the protected service method
 The protected service method calls the doGet method depending on the
type of request.
 The doGet method generates the response and it is passed to the client.
 After sending the response, the web container deletes the request and
response objects. The thread is contained in the thread pool or deleted
depends on the server implementation.
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.
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);
}
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.
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);
} //POST Code goes here
} }
Invoking Servlet From
HTML using GenericServlet
Invoking Servlet From HTML(index.html)
<html>
<head> <TITLE>INVOKING SERVLET FROM HTML </TITLE> </head>
<BODY> <FORM name = "PostParam" method = "Post" action="Server">
<TABLE> <tr>
<td> <B>Employee: </B> </td>
<td><input type = "textbox" name="ename" size="25“ value=""></td>
</tr> </TABLE>
<INPUT type = "submit" value="Submit">
</FORM>
</body>
</html>
Invoking Servlet From HTML(Server.java)
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/Server")
public class Server extends GenericServlet {
public void service(ServletRequest request,ServletResponse response)throws
ServletException,IOException
{ PrintWriter out=response.getWriter();
String name=request.getParameter("ename");
out.println("EmployeeName: "+name);
} }
Invoking Servlet From HTML(web.xml)
<?xml version="1.0" encoding="UTF-8"?>
<element> <web-app>
<display-name>invokehtml</display-name>
<servlet> <servlet-name>as</servlet-name>
<servlet-class>Server</servlet-class> </servlet>
<servlet-mapping> <servlet-name>as</servlet-name>
<url-pattern>/Server</url-pattern> </servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app> </element>
Invoking Servlet From
HTML using HttpServlet
Invoking Servlet From HTML(index.html)
<html>
<head> <TITLE>INVOKING SERVLET FROM HTML </TITLE> </head>
<BODY> <FORM name = "PostParam" method = “get" action="Server">
<TABLE> <tr>
<td> <B>Employee: </B> </td>
<td><input type = "textbox" name="ename" size="25“ value=""></td>
</tr> </TABLE>
<INPUT type = "submit" value="Submit">
</FORM>
</body>
</html>
Invoking Servlet From HTML (Server.java)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/Server")
public class Server extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse
response)throws ServletException,IOException
{ PrintWriter out=response.getWriter();
String name=request.getParameter("ename");
out.println("EmployeeNa: "+name); } }
Invoking Servlet From HTML(web.xml)
<?xml version="1.0" encoding="UTF-8"?>
<element> <web-app>
<display-name>invokehtml</display-name>
<servlet> <servlet-name>as</servlet-name>
<servlet-class>Server</servlet-class> </servlet>
<servlet-mapping> <servlet-name>as</servlet-name>
<url-pattern>/Server</url-pattern> </servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app> </element>
Session
Tracking/Handling
in Servlets
Introduction
 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.
Introduction
 HTTP is stateless that means each request is
considered as the new request. It is shown in the
figure given below:
Why use Session Tracking?
 To recognize the user It is used to recognize the
particular user.
Session Tracking Techniques
There are four techniques used in Session
tracking:
Cookies
Hidden Form Field
URL Rewriting
HttpSession
Cookies in Servlet
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.
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.
How Cookie works
Types of Cookie
There are 2 types of cookies in servlets.
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.
Advantage/Disadvantage of Cookies
Advantage
Simplest technique of maintaining the state.
Cookies are maintained at client side.
Disadvantage
It will not work if cookie is disabled from the
browser.
Only textual information can be set in Cookie object.
Methods of Cookie class
 javax.servlet.http.Cookie class provides the
functionality of using cookies. It provides a lot of useful
methods for cookies.
Method Description
public void setMaxAge(int
expiry)
Sets the maximum age of the cookie in
seconds.
public String getName()
Returns the name of the cookie. The
name cannot be changed after creation.
public String getValue() Returns the value of the cookie.
public void setName(String
name)
changes the name of the cookie.
public void setValue(String value) changes the value of the cookie.
How to create Cookie?
//creating cookie object
Cookie c=new Cookie("user",“Newton");
//adding cookie in the response
response.addCookie(c);
How to delete Cookie?
//deleting value of cookie
Cookie c=new Cookie("user","");
//changing the maximum age to 0 seconds
c.setMaxAge(0);
//adding cookie in the response
response.addCookie(c);
How to get Cookies?
Cookie c[]=request.getCookies();
for(int i=0;i<c.length;i++)
{
out.print("<br>"+c[i].getName()+" "+c[i].getValue());
}
Simple example of Servlet Cookies
Index.html
<form action="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
Cookie ck=new Cookie("uname",n);//creating cookie object
response.addCookie(ck);//adding cookie in the response
out.print("<form action='servlet2‘ method=‘post’>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();
}catch(Exception e){System.out.println(e); } }
SecondServlet.java
try{
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); } }
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>
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.
 It is widely used in comment form of a website to store
page id or page name in the hidden field so that each
page can be uniquely identified.
 code to store value in hidden field
<input type="hidden" name="uname" value="Vimal ">
Advantage/Disadvantage of Hidden Form Fields
Advantage
It will always work whether cookie is disabled or not.
Disadvantage
It is maintained at server side.
Extra form submission is required on each pages.
Only textual information can be used.
Index.html
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
out.print("<form action='servlet2‘ method=‘post’>");
out.print("<input type='hidden' name='uname' value='"+n+"'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();
}catch(Exception e){System.out.println(e); } }
SecondServlet.java
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){
System.out.println(e); } }
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>
URL Rewriting
 In URL rewriting, we append a token or identifier to the URL of the
next Servlet or the next resource.
 We can send parameter name/value pairs using the following format:
url?name1=value1&name2=value2&??
 A name and a value is separated using an equal = sign,
 A parameter name/value pair is separated from another parameter
using the ampersand(&).
 When the user clicks the hyperlink, the parameter name/value pairs
will be passed to the server.
 From a Servlet, we can use getParameter() method to obtain a
parameter value.
Advantage/Disadvantage of URL Rewriting
Advantage
It will always work whether cookie is disabled or not
(browser independent).
Extra form submission is not required on each pages.
Disadvantage
It will work only with links.
It can send Only textual information.
Index.html
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
out.print("<a href='servlet2?uname="+n+"'>visit</a>");
out.close();
}catch(Exception e){System.out.println(e); } }
SecondServlet.java
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){
System.out.println(e); } }
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>
HttpSession interface
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:
bind objects
view and manipulate information about a session, such
as the session identifier, creation time, and last
accessed time.
HttpSession interface
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, returns a new session.
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.
Index.html
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
try{
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); } }
SecondServlet.java
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session=request.getSession(false);
String n=request.getParameter("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){
System.out.println(e); } }
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>

Weitere ähnliche Inhalte

Was ist angesagt?

Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
parag
 
Java: The Complete Reference, Eleventh Edition
Java: The Complete Reference, Eleventh EditionJava: The Complete Reference, Eleventh Edition
Java: The Complete Reference, Eleventh Edition
moxuji
 

Was ist angesagt? (20)

Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Enterprise java unit-2_chapter-2
Enterprise  java unit-2_chapter-2Enterprise  java unit-2_chapter-2
Enterprise java unit-2_chapter-2
 
Java: The Complete Reference, Eleventh Edition
Java: The Complete Reference, Eleventh EditionJava: The Complete Reference, Eleventh Edition
Java: The Complete Reference, Eleventh Edition
 
Session tracking In Java
Session tracking In JavaSession tracking In Java
Session tracking In Java
 
Jsp element
Jsp elementJsp element
Jsp element
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
 
Servlet and servlet life cycle
Servlet and servlet life cycleServlet and servlet life cycle
Servlet and servlet life cycle
 
Java threading
Java threadingJava threading
Java threading
 
Enterprise java unit-1_chapter-3
Enterprise java unit-1_chapter-3Enterprise java unit-1_chapter-3
Enterprise java unit-1_chapter-3
 
Jsp(java server pages)
Jsp(java server pages)Jsp(java server pages)
Jsp(java server pages)
 
JAVA PROGRAMMING - The Collections Framework
JAVA PROGRAMMING - The Collections Framework JAVA PROGRAMMING - The Collections Framework
JAVA PROGRAMMING - The Collections Framework
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
JAVA Collections frame work ppt
 JAVA Collections frame work ppt JAVA Collections frame work ppt
JAVA Collections frame work ppt
 
Advance Java Programming (CM5I) 6.Servlet
Advance Java Programming (CM5I) 6.ServletAdvance Java Programming (CM5I) 6.Servlet
Advance Java Programming (CM5I) 6.Servlet
 
JDBC
JDBCJDBC
JDBC
 

Ähnlich wie Java Servlet

Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
Jafar Nesargi
 
Jsp and Servlets
Jsp and ServletsJsp and Servlets
Jsp and Servlets
Raghu nath
 
S E R V L E T S
S E R V L E T SS E R V L E T S
S E R V L E T S
patinijava
 

Ähnlich wie Java Servlet (20)

J servlets
J servletsJ servlets
J servlets
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
 
Servlet 01
Servlet 01Servlet 01
Servlet 01
 
SERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMINGSERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMING
 
Wt unit 3
Wt unit 3 Wt unit 3
Wt unit 3
 
Java servlets
Java servletsJava servlets
Java servlets
 
Servlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, APIServlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, API
 
Jsp and Servlets
Jsp and ServletsJsp and Servlets
Jsp and Servlets
 
J2ee servlet
J2ee servletJ2ee servlet
J2ee servlet
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technology
 
TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtap
 
Weblogic
WeblogicWeblogic
Weblogic
 
Servlet by Rj
Servlet by RjServlet by Rj
Servlet by Rj
 
S E R V L E T S
S E R V L E T SS E R V L E T S
S E R V L E T S
 
Servlet.pptx
Servlet.pptxServlet.pptx
Servlet.pptx
 
Servlet.pptx
Servlet.pptxServlet.pptx
Servlet.pptx
 
Servlets
ServletsServlets
Servlets
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java Servlet
 

Mehr von Yoga Raja (10)

Ajax
AjaxAjax
Ajax
 
Php
PhpPhp
Php
 
Xml
XmlXml
Xml
 
Database connect
Database connectDatabase connect
Database connect
 
JSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGESJSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGES
 
JSON
JSONJSON
JSON
 
Java script
Java scriptJava script
Java script
 
Think-Pair-Share
Think-Pair-ShareThink-Pair-Share
Think-Pair-Share
 
Minute paper
Minute paperMinute paper
Minute paper
 
Decision support system-MIS
Decision support system-MISDecision support system-MIS
Decision support system-MIS
 

Kürzlich hochgeladen

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 

Kürzlich hochgeladen (20)

Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 

Java Servlet

  • 1. Java Servlet Prepared By Yogaraja C A Ramco Institute of Technology
  • 2. Definition  Servlet technology is used to create a web application (resides at server side and generates a dynamic web page).  Before Servlet, CGI (Common Gateway Interface) scripting language was common as a server-side programming language.  Servlet is an interface that must be implemented for creating any Servlet.  Servlet is a class that extends the capabilities of the servers and responds to the incoming requests. It can respond to any requests.
  • 3.
  • 4. CGI (Common Gateway Interface)  CGI technology enables the web server to call an external program and pass HTTP request information to the external program to process the request. For each request, it starts a new process.
  • 5. Disadvantages of CGI  If the number of clients increases, it takes more time for sending the response.  For each request, it starts a process, and the web server is limited to start processes.  It uses platform dependent language e.g. C, C++, perl.
  • 6. Advantages of Servlet The web container creates threads for handling the multiple requests to the Servlet. Threads have many benefits over the Processes such as they share a common memory area, lightweight, cost of communication between the threads are low.  Better performance: because it creates a thread for each request, not process.  Portability: because it uses Java language.  Robust: JVM manages Servlets, so we don't need to worry about the memory leak, garbage collection, etc.  Secure: because it uses java language.
  • 7. Static vs Dynamic website Static Website Dynamic Website Prebuilt content is same every time the page is loaded. Content is generated quickly and changes regularly. It uses the HTML code for developing a website. It uses the server side languages such as PHP,SERVLET, JSP, and ASP.NET etc. for developing a website. It sends exactly the same response for every request. It may generate different HTML for each of the request. The content is only changed when someone publishes and updates the file (sends it to the web server). The page contains "server-side" code which allows the server to generate the unique content when the page is loaded. Flexibility is the main advantage of static website. Content Management System (CMS) is the main advantage of dynamic website.
  • 8. Servlet Container  It provides the runtime environment for JavaEE (j2ee) applications. The client/user can request only a static WebPages from the server. If the user wants to read the web pages as per input then the servlet container is used in java.  The servlet container is the part of web server which can be run in a separate process. We can classify the servlet container states in three types:
  • 9. Servlet Container States The servlet container is the part of web server which can be run in a separate process. We can classify the servlet container states in three types:  Standalone: It is typical Java-based servers in which the servlet container and the web servers are the integral part of a single program. For example:- Tomcat running by itself  In-process: It is separated from the web server, because a different program runs within the address space of the main server as a plug-in. For example:- Tomcat running inside the JBoss.  Out-of-process: The web server and servlet container are different programs which are run in a different process. For performing the communications between them, web server uses the plug-in provided by the servlet container.
  • 10. Servlets - Life Cycle/Architecture A servlet life cycle can be defined as the entire process from its creation till the destruction.  The servlet is initialized by calling the init() method.  The servlet calls service() method to process a client's request.  The servlet is terminated by calling the destroy() method.  Finally, servlet is garbage collected by the garbage collector of the JVM.
  • 11.
  • 12. Steps to create a servlet To create servlet using apache tomcat server, 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
  • 13. 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.
  • 14.
  • 15. Create a servlet 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.
  • 16. Compile the servlet For compiling the Servlet, jar file is required to be loaded. Different Servers provide different jar files: jar file Server servlet-api.jar Apache Tomcat weblogic.jar Weblogic javaee.jar Glassfish javaee.jar JBoss
  • 17. Create the deployment descriptor (web.xml file) The deployment descriptor is an xml file, from which Web Container gets the information about the servlet 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.
  • 19. Web.xml Description <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.
  • 21. Servlet Interface  Servlet interface provides common behavior to all the servlets. Servlet interface defines methods that all servlets must implement.  Servlet interface needs to be implemented for creating any servlet (either directly or indirectly).  It provides 3 life cycle methods that are used to initialize the servlet, to service the requests, and to destroy the servlet and 2 non-life cycle methods.
  • 22. Methods of Servlet interface Method Description public void init(ServletConfig config) initializes the servlet. It is the life cycle method of servlet and invoked by the web container only once. public void service(ServletRequest request,ServletResponse response) provides response for the incoming request. It is invoked at each request by the web container. public void destroy() is invoked only once 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.
  • 23. Servlet Example by implementing Servlet interface public class First implements Servlet { ServletConfig config=null; public void init(ServletConfig config){ System.out.println("servlet is initialized"); } public void service(ServletRequest req,ServletResponse res) throws IOException,ServletException{ res.setContentType("text/html"); PrintWriter out=res.getWriter(); out.print("<html><body>"); out.print("<b>hello simple servlet </b>"); out.print("</body></html>"); } }
  • 24. GenericServlet class GenericServlet class implements Servlet, ServletConfig and Serializable interfaces. 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.
  • 25. Methods of GenericServlet class  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 void log(String msg) writes the given message in the servlet log file.
  • 26. Servlet by inheriting the GenericServlet class public class First extends GenericServlet{ public void service(ServletRequest req,ServletResponse res) throws IOException,ServletException { res.setContentType("text/html"); PrintWriter out=res.getWriter(); out.print("<html><body>"); out.print("<b>hello generic servlet</b>"); out.print("</body></html>"); } }
  • 27. HttpServlet class The HttpServlet class extends the GenericServlet class and implements Serializable interface. It provides http specific methods such as doGet, doPost, doHead, doTrace etc.
  • 28. Methods of HttpServlet class  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.
  • 29. Methods of HttpServlet class  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.
  • 30. Servlet by inheriting the HttpServlet class public class First extends HttpServlet{ public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { res.setContentType("text/html"); PrintWriter pw=res.getWriter(); pw.println("<html><body>"); pw.println("Welcome to servlet"); pw.println("</body></html>"); pw.close(); }}
  • 32. How Servlet works?  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.
  • 33. How web container handles the servlet request? The web container is responsible to handle the request.  maps the request with the servlet in the web.xml file.  creates request and response objects for this request  calls the service method on the thread  The public service method internally calls the protected service method  The protected service method calls the doGet method depending on the type of request.  The doGet method generates the response and it is passed to the client.  After sending the response, the web container deletes the request and response objects. The thread is contained in the thread pool or deleted depends on the server implementation.
  • 34. 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.
  • 35. 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); }
  • 36. 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.
  • 37. 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); } //POST Code goes here } }
  • 38. Invoking Servlet From HTML using GenericServlet
  • 39. Invoking Servlet From HTML(index.html) <html> <head> <TITLE>INVOKING SERVLET FROM HTML </TITLE> </head> <BODY> <FORM name = "PostParam" method = "Post" action="Server"> <TABLE> <tr> <td> <B>Employee: </B> </td> <td><input type = "textbox" name="ename" size="25“ value=""></td> </tr> </TABLE> <INPUT type = "submit" value="Submit"> </FORM> </body> </html>
  • 40. Invoking Servlet From HTML(Server.java) import java.io.*; import javax.servlet.*; import javax.servlet.annotation.WebServlet; @WebServlet("/Server") public class Server extends GenericServlet { public void service(ServletRequest request,ServletResponse response)throws ServletException,IOException { PrintWriter out=response.getWriter(); String name=request.getParameter("ename"); out.println("EmployeeName: "+name); } }
  • 41. Invoking Servlet From HTML(web.xml) <?xml version="1.0" encoding="UTF-8"?> <element> <web-app> <display-name>invokehtml</display-name> <servlet> <servlet-name>as</servlet-name> <servlet-class>Server</servlet-class> </servlet> <servlet-mapping> <servlet-name>as</servlet-name> <url-pattern>/Server</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app> </element>
  • 42. Invoking Servlet From HTML using HttpServlet
  • 43. Invoking Servlet From HTML(index.html) <html> <head> <TITLE>INVOKING SERVLET FROM HTML </TITLE> </head> <BODY> <FORM name = "PostParam" method = “get" action="Server"> <TABLE> <tr> <td> <B>Employee: </B> </td> <td><input type = "textbox" name="ename" size="25“ value=""></td> </tr> </TABLE> <INPUT type = "submit" value="Submit"> </FORM> </body> </html>
  • 44. Invoking Servlet From HTML (Server.java) import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.annotation.WebServlet; @WebServlet("/Server") public class Server extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException { PrintWriter out=response.getWriter(); String name=request.getParameter("ename"); out.println("EmployeeNa: "+name); } }
  • 45. Invoking Servlet From HTML(web.xml) <?xml version="1.0" encoding="UTF-8"?> <element> <web-app> <display-name>invokehtml</display-name> <servlet> <servlet-name>as</servlet-name> <servlet-class>Server</servlet-class> </servlet> <servlet-mapping> <servlet-name>as</servlet-name> <url-pattern>/Server</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app> </element>
  • 47. Introduction  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.
  • 48. Introduction  HTTP is stateless that means each request is considered as the new request. It is shown in the figure given below: Why use Session Tracking?  To recognize the user It is used to recognize the particular user.
  • 49. Session Tracking Techniques There are four techniques used in Session tracking: Cookies Hidden Form Field URL Rewriting HttpSession
  • 50. Cookies in Servlet 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.
  • 51. 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.
  • 53. Types of Cookie There are 2 types of cookies in servlets. 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.
  • 54. Advantage/Disadvantage of Cookies Advantage Simplest technique of maintaining the state. Cookies are maintained at client side. Disadvantage It will not work if cookie is disabled from the browser. Only textual information can be set in Cookie object.
  • 55. Methods of Cookie class  javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of useful methods for cookies. Method Description public void setMaxAge(int expiry) Sets the maximum age of the cookie in seconds. public String getName() Returns the name of the cookie. The name cannot be changed after creation. public String getValue() Returns the value of the cookie. public void setName(String name) changes the name of the cookie. public void setValue(String value) changes the value of the cookie.
  • 56. How to create Cookie? //creating cookie object Cookie c=new Cookie("user",“Newton"); //adding cookie in the response response.addCookie(c);
  • 57. How to delete Cookie? //deleting value of cookie Cookie c=new Cookie("user",""); //changing the maximum age to 0 seconds c.setMaxAge(0); //adding cookie in the response response.addCookie(c);
  • 58. How to get Cookies? Cookie c[]=request.getCookies(); for(int i=0;i<c.length;i++) { out.print("<br>"+c[i].getName()+" "+c[i].getValue()); }
  • 59. Simple example of Servlet Cookies
  • 60. Index.html <form action="servlet1" method="post"> Name:<input type="text" name="userName"/><br/> <input type="submit" value="go"/> </form>
  • 61. FirstServlet.java try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("userName"); out.print("Welcome "+n); Cookie ck=new Cookie("uname",n);//creating cookie object response.addCookie(ck);//adding cookie in the response out.print("<form action='servlet2‘ method=‘post’>"); out.print("<input type='submit' value='go'>"); out.print("</form>"); out.close(); }catch(Exception e){System.out.println(e); } }
  • 62. SecondServlet.java try{ 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); } }
  • 63. 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>
  • 64. 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.  It is widely used in comment form of a website to store page id or page name in the hidden field so that each page can be uniquely identified.  code to store value in hidden field <input type="hidden" name="uname" value="Vimal ">
  • 65. Advantage/Disadvantage of Hidden Form Fields Advantage It will always work whether cookie is disabled or not. Disadvantage It is maintained at server side. Extra form submission is required on each pages. Only textual information can be used.
  • 66. Index.html <form action="servlet1"> Name:<input type="text" name="userName"/><br/> <input type="submit" value="go"/> </form>
  • 67. FirstServlet.java try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("userName"); out.print("Welcome "+n); out.print("<form action='servlet2‘ method=‘post’>"); out.print("<input type='hidden' name='uname' value='"+n+"'>"); out.print("<input type='submit' value='go'>"); out.print("</form>"); out.close(); }catch(Exception e){System.out.println(e); } }
  • 68. SecondServlet.java try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("uname"); out.print("Hello "+n); out.close(); }catch(Exception e){ System.out.println(e); } }
  • 69. 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>
  • 70. URL Rewriting  In URL rewriting, we append a token or identifier to the URL of the next Servlet or the next resource.  We can send parameter name/value pairs using the following format: url?name1=value1&name2=value2&??  A name and a value is separated using an equal = sign,  A parameter name/value pair is separated from another parameter using the ampersand(&).  When the user clicks the hyperlink, the parameter name/value pairs will be passed to the server.  From a Servlet, we can use getParameter() method to obtain a parameter value.
  • 71. Advantage/Disadvantage of URL Rewriting Advantage It will always work whether cookie is disabled or not (browser independent). Extra form submission is not required on each pages. Disadvantage It will work only with links. It can send Only textual information.
  • 72. Index.html <form action="servlet1"> Name:<input type="text" name="userName"/><br/> <input type="submit" value="go"/> </form>
  • 73. FirstServlet.java try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("userName"); out.print("Welcome "+n); out.print("<a href='servlet2?uname="+n+"'>visit</a>"); out.close(); }catch(Exception e){System.out.println(e); } }
  • 74. SecondServlet.java try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("uname"); out.print("Hello "+n); out.close(); }catch(Exception e){ System.out.println(e); } }
  • 75. 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>
  • 76. HttpSession interface 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: bind objects view and manipulate information about a session, such as the session identifier, creation time, and last accessed time.
  • 78. 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, returns a new session.
  • 79. 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.
  • 80. Index.html <form action="servlet1"> Name:<input type="text" name="userName"/><br/> <input type="submit" value="go"/> </form>
  • 81. FirstServlet.java try{ 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); } }
  • 82. SecondServlet.java try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); HttpSession session=request.getSession(false); String n=request.getParameter("uname"); out.print("Hello "+n); out.close(); }catch(Exception e){ System.out.println(e); } }
  • 83. 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>