SlideShare a Scribd company logo
Wt unit 3
UNIT-3
Introduction to Servlets
Concepts of CGI
What is CGI ?
The Common Gateway Interface, or CGI, is a set of standards
that define how information is exchanged between the web
server and a custom script.
The Common Gateway Interface, or CGI, is a standard for
external gateway programs to interface with information
servers such as HTTP servers.
Concepts of CGI
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.
Concepts of CGI
CGI Architecture Diagram
Disadvantages of CGI
There are many problems in CGI technology:
1. If number of clients increases, it takes more time for sending
response.
2. For each request, it starts a process and Web server is limited
to start processes.
3. It uses platform dependent language e.g. C, C++, perl.
Concepts of Servlets
What is a Servlet?
Servlet can be described in many ways, depending on the context.
•Servlet is a technology i.e. used to create web application.
•Servlet is an API that provides many interfaces and classes
including documentations.
•Servlet is an interface that must be implemented for creating any
servlet.
•Servlet is a class that extend the capabilities of the servers and
respond to the incoming request. It can respond to any type of
requests.
•Servlet is a web component that is deployed on the server to
create dynamic web page.
Concepts of Servlets
Concepts of Servlets
Advantage of Servlet
There are many advantages of servlet over CGI.
The basic benefits of servlet are as follows:
•better performance: because it creates a thread for each request
not process.
•Portability: because it uses java language.
•Robust: Servlets are managed by JVM so we don't need to worry
about memory leak, garbage collection etc.
•Secure: because it uses java language..
Concepts of Servlets
Advantage of Servlet
The web container creates threads for handling the multiple requests to the
servlet.
Threads have a lot of benefits over the Processes such as they share a common
memory area, lightweight, cost of communication between the threads are low.
Concepts of Servlets
Life Cycle of a Servlet (Servlet Life Cycle)
The web container maintains the life cycle of a servlet instance.
Let's see the life cycle of the servlet:
Servlet class is loaded.
Servlet instance is created.
init method is invoked.
service method is invoked.
destroy method is invoked.
Concepts of Servlets
Life Cycle of a Servlet (Servlet Life Cycle)
Concepts of Servlets
Servlet Life Cycle methods
The init() Method:
The init method is called only once.
It is called only when the servlet is created, and not
called for any user requests afterwards.
The init method definition looks like this −
public void init() throws ServletException
{
// Initialization code...
}
Concepts of Servlets
Servlet Life Cycle methods(cont..)
The service() Method
The service() method is the main method to perform the
actual task.
The servlet container (i.e. web server) calls the service()
method to handle requests coming from the client(
browsers) and to write the formatted response back to
the client.
The service() method checks the HTTP request type
(GET, POST, PUT, DELETE, etc.) and calls doGet, doPost,
doPut, doDelete, etc. methods as appropriate.
Concepts of Servlets
Servlet Life Cycle methods(cont..)
The service() Method
Here is the signature of this method −
public void service(ServletRequest request, ServletResponse response) throws
ServletException, IOException
{
…..
…
}
We have nothing to do with service() method but you override
either doGet() or doPost() depending on what type of request
you receive from the client.
Concepts of Servlets
Servlet Life Cycle methods(cont..)
The destroy() Method
The destroy() method is called only once at the end of
the life cycle of a servlet.
This method gives your servlet a chance to close
database connections, halt background threads, write
cookie lists or hit counts to disk, and perform other such
cleanup activities.
public void destroy()
{ // Finalization code...
}
Concepts of Servlets
Servlet Life Cycle Scenario
Sample Code of Servlets
//Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloWorld extends HttpServlet {
private String message;
public void init() throws ServletException {
// Do required initialization
message = "Hello World";
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
// Actual logic goes here.
PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}
public void destroy() {
// do nothing.
}
}
Compiling Servlets
Compiling a Servlet:
1. Let us create a file with name HelloWorld.java with the code
shown above.
2. Place this file at C:ServletDevel (in Windows) or at
/usr/ServletDevel (in Unix).
3. This path location must be added to CLASSPATH before
proceeding further.
4. Assuming your environment is setup properly, go
in ServletDevel directory and compile HelloWorld.java as follows
−
$ javac HelloWorld.java
Compiling Servlets(con..)
5. If the servlet depends on any other libraries, you have to
include those JAR files on your CLASSPATH as well.
6. Include only servlet-api.jar JAR file because if you are not
using any other library in Hello World program.
7. If everything goes fine, above compilation would
produce HelloWorld.class file in the same directory.
Next section would explain how a compiled servlet would be
deployed in production.
Servlets Deployment
Servlet Deployment:
Step 1: By default,
A servlet application is located at the path
<Tomcat-installationdirectory>/webapps/ROOT
and
the class file would reside in
<Tomcat-installationdirectory>/webapps/ROOT/WEB-
INF/classes.
If you have a fully qualified class name,
of com.myorg.MyServlet then this servlet class must be
located in WEB-INF/classes/com/myorg/MyServlet.class.
Servlets Deployment(con..)
Step 2:
let us copy HelloWorld.class into
<Tomcat-installationdirectory>/webapps/ROOT/WEB-
INF/classes
Step 3:
create following entries in web.xml file located in
<Tomcat-installation-directory>/webapps/ROOT/WEB-INF/
Servlets Deployment(cont..)
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
Above entries to be created inside <web-app>...</web-app> tags
available in web.xml file.
Servlets Deployment(cont..)
Step 4:
Start tomcat server using
<Tomcat-installationdirectory>binstartup.bat (on
Windows) or
<Tomcat-installationdirectory>/bin/startup.sh (on
Linux/Solaris etc.) and
Step 5:finally type
http://localhost:8080/HelloWorld
in the browser's address box.
Servlets Deployment(cont..)
Servlet API
The javax.servlet and javax.servlet.http packages
represent interfaces and classes for servlet api.
The javax.servlet package contains many
interfaces and classes that are used by the servlet or
web container. These are not specific to any
protocol.
The javax.servlet.http package contains interfaces
and classes that are responsible for http requests
only.
Servlets Deployment(cont..)
There are many interfaces in javax.servlet package. They are as
follows:
1. Servlet
2. ServletRequest
3. ServletResponse
4. RequestDispatcher
5. ServletConfig
6. ServletContext
7. SingleThreadModel
8. Filter
9. FilterConfig
10. FilterChain
11. ServletRequestListener
12. ServletRequestAttributeListener
13. ServletContextListener
14. ServletContextAttributeListener
Servlets Deployment(cont..)
There are many classes in javax.servlet package. They are as follows:
1. GenericServlet
2. ServletInputStream
3. ServletOutputStream
4. ServletRequestWrapper
5. ServletResponseWrapper
6. ServletRequestEvent
7. ServletContextEvent
8. ServletRequestAttributeEvent
9. ServletContextAttributeEvent
10. ServletException
11. UnavailableException
Servlets Deployment(cont..)
Interfaces in javax.servlet.http package
1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
4. HttpSessionListener
5. HttpSessionAttributeListener
6. HttpSessionBindingListener
7. HttpSessionActivationListener
8. HttpSessionContext (deprecated now)
Servlets Deployment(cont..)
Classes in javax.servlet.http package
1. HttpServlet
2. Cookie
3. HttpServletRequestWrapper
4. HttpServletResponseWrapper
5. HttpSessionEvent
6. HttpSessionBindingEvent
7. HttpUtils (deprecated now)
Servlets Deployment(cont..)
Parameters in Servlets
The parameters are the way in which a client or user can
send information to the Http Server
Servlets Deployment(cont..)
Parameters in Servlets
For example,
in a login screen, we need to send to the server, the user
and the password so that it validates them.
Servlets Deployment(cont..)
Parameters in Servlets
For example,
How does the client or the Browser send these parameters
using the methods GET or POST,
The first thing we are going to do is to create in our site a page
"login.html" with the following content:
<html>
<body>
<form action="login" method="get">
<table>
<tr>
<td>User</td>
<td><input name="user" /></td>
</tr>
<tr>
<td>password</td>
<td><input name="password" /></td>
</tr>
</table>
<input type="submit" />
</form>
</body>
</html>
Servlets Deployment(cont..)
Parameters in Servlets
Then, we create a Servlet which receives the request
in /login , which is the indicated direction in
the action attribute of the tag <form> of login.html
Servlets Deployment(cont..)
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String user = req.getParameter("user");
String pass = req.getParameter("password");
if ("edu4java".equals(user) && "eli4java".equals(pass)) {
response(resp, "login ok");
} else {
response(resp, "invalid login");
}
}
Servlets Deployment(cont..)
private void response(HttpServletResponse resp, String msg)
throws IOException {
PrintWriter out = resp.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<t1>" + msg + "</t1>");
out.println("</body>");
out.println("</html>");
}
}
Servlets Deployment(cont..)
We modify web.xml to link /login with this Servlet.
<web-app>
<servlet>
<servlet-name>timeservlet</servlet-name>
<servlet-class>com.edu4java.servlets.FirstServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>login-servlet</servlet-name>
<servlet-class>com.edu4java.servlets.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>timeservlet</servlet-name>
<url-pattern>/what-time-is-it</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>login-servlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
Servlets Deployment(cont..)
Session Tracking and Cookies
Session Tracking:
Keeping track of a sequence of related requests sent
by a client to perform some designated task is known
as “Session Tracking”
Cookies are one of the solutions to session tracking.
Servlets Deployment(cont..)
Session Tracking and Cookies(cont..)
Cookies:
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.
Servlets Deployment(cont..)
Session Tracking and Cookies(cont..)
How Cookies Work:
Servlets Deployment(cont..)
Session Tracking and Cookies(cont..)
How Cookies Work:
•By default, each request is considered as a new request.
•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.
•we recognize the user as the old user.
Servlets Deployment(cont..)
Session Tracking and Cookies(cont..)
How Cookies Work:
•By default, each request is considered as a new request.
•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.
•we recognize the user as the old user.
Servlets Deployment(cont..)
Session Tracking and Cookies(cont..)
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.
Servlets Deployment(cont..)
Session Tracking and Cookies(cont..)
Advantage of Cookies
Simplest technique of maintaining the state.
Cookies are maintained at client side.
Disadvantage of Cookies
It will not work if cookie is disabled from the browser.
Only textual information can be set in Cookie object.
Servlets Deployment(cont..)
Session Tracking and Cookies(cont..)
Cookie class
javax.servlet.http.Cookie class provides the functionality
of using cookies. It provides a lot of useful methods for
cookies.
Servlets Deployment(cont..)
Session Tracking and Cookies(cont..)
Constructor of Cookie class
Cookie() : constructs a cookie.
Cookie(String name, String value) : constructs a cookie
with a specified name and value.
Servlets Deployment(cont..)
Session Tracking and Cookies(cont..)
Method Descriptionpublic
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
Servlets Deployment(cont..)
Session Tracking and Cookies(cont..)
How to send Cookies to the Client( 3 steps )
1) Create a Cookie object.
Cookie c = new Cookie("userName",”Vits");
2) Set the maximum Age:
c.setMaxAge(1800); // value in seconds
3) Place the Cookie in HTTP response header:
response.addCookie(c);
Servlets Deployment(cont..)
Session Tracking and Cookies(cont..)
How to Read Cookies from the Client/browser
Cookie c[]=request.getCookies(); //c.length gives the cookie
count
for(int i=0;i<c.length;i++)
{
out.print("Name: "+c[i].getName()+" & Value:
"+c[i].getValue());
}
Servlets Deployment(cont..)
Session Tracking and Cookies(cont..)
How to delete Cookies from the Client/browser
If you want to delete a cookie then you simply need to follow up following
three steps −
Read an already existing cookie and store it in Cookie object.
Set cookie age as zero using setMaxAge() method to delete an existing
cookie
Add this cookie back into response header.
Servlets Deployment(cont..)
Session Tracking and Cookies(cont..)
How to delete Cookies from the Client/browser
Let's see the simple code to delete cookie.
It is mainly used to logout or sign out the user.
Cookie ck=new Cookie("user",""); //deleting value of cookie
ck.setMaxAge(0); //changing the maximum age to 0 seconds
response.addCookie(ck); //adding cookie in the response
Servlets Deployment(cont..)
Session Tracking and Cookies(cont..)
Http Sessions
A session contains information specific to a particular user
across the whole application.
In such case, container creates a session id for each user.
The container uses this id to identify the particular user.
This unique ID can be stored into a cookie or in a request
parameter.
The HttpSession stays alive until it has not been used for
more than the timeout value specified in tag in deployment
descriptor file.
The default timeout value is 30 minutes, this is used if you
don’t specify the value in tag.
Servlets Deployment(cont..)
Session Tracking and Cookies(cont..)
Http Sessions(cont..)
Servlets Deployment(cont..)
Session Tracking and Cookies(cont..)
Http Sessions(cont..)
This is how you create a HttpSession object.
protected void doPost(HttpServletRequest req,
HttpServletResponse res) throws ServletException,
IOException
{
HttpSession session = req.getSession();
}
Servlets Deployment(cont..)
Http Sessions(cont..)
How you can store user information in
HttpSession object.
setAttribute(): method stores user information session
object
later when needed this information can be fetched from
the session.
Servlets Deployment(cont..)
Http Sessions(cont..)
How you can store user information in
HttpSession object.
Example: storing username, email-id and user age in
session with the attribute name uName, uemailId and
uAge respectively.
session.setAttribute("uName", "Chaitanya");
session.setAttribute("uemailId", "myemailid@gmail.com");
session.setAttribute("uAge", "30");
Servlets Deployment(cont..)
Http Sessions(cont..)
TO get the value from session we use the
getAttribute() method of HttpSession interface.
Example:
String userName = (String) session.getAttribute("uName");
String userEmailId = (String) session.getAttribute("uemailId");
String userAge = (String) session.getAttribute("uAge");
Servlets Deployment(cont..)
Http Sessions(cont..)
Sr.No. Method & Description
1
public Object getAttribute(String name)
This method returns the object bound with the specified
name in this session, or null if no object is bound under
the name.
2
public Enumeration getAttributeNames()
This method returns an Enumeration of String objects
containing the names of all the objects bound to this
session.
3
public long getCreationTime()
This method returns the time when this session was
created, measured in milliseconds since midnight January
1, 1970 GMT.
4
public String getId()
This method returns a string containing the unique
identifier assigned to this session.
Servlets Deployment(cont..)
Http Sessions(cont..)
Sr.No. Method & Description
5
public long getLastAccessedTime()
This method returns the last accessed time of the session,
in the format of milliseconds since midnight January 1,
1970 GMT
6
public int getMaxInactiveInterval()
This method returns the maximum time interval
(seconds), that the servlet container will keep the session
open between client accesses.
7
public void invalidate()
This method invalidates this session and unbinds any
objects bound to it.
8
public boolean isNew()
This method returns true if the client does not yet know
about the session or if the client chooses not to join the
session.
Servlets Deployment(cont..)
Http Sessions(cont..)
Sr.No. Method & Description
9
public void removeAttribute(String name)
This method removes the object bound with the specified
name from this session.
10
public void setAttribute(String name, Object value)
This method binds an object to this session, using the
name specified.
11
public void setMaxInactiveInterval(int interval)
This method specifies the time, in seconds, between client
requests before the servlet container will invalidate this
session.
Ad

More Related Content

What's hot (20)

Css lecture notes
Css lecture notesCss lecture notes
Css lecture notes
Santhiya Grace
 
Sgml
SgmlSgml
Sgml
rahul kundu
 
Servlets
ServletsServlets
Servlets
ZainabNoorGul
 
Enterprise java unit-3_chapter-1-jsp
Enterprise  java unit-3_chapter-1-jspEnterprise  java unit-3_chapter-1-jsp
Enterprise java unit-3_chapter-1-jsp
sandeep54552
 
Databind in asp.net
Databind in asp.netDatabind in asp.net
Databind in asp.net
Sireesh K
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packages
vamsi krishna
 
Mining single dimensional boolean association rules from transactional
Mining single dimensional boolean association rules from transactionalMining single dimensional boolean association rules from transactional
Mining single dimensional boolean association rules from transactional
ramya marichamy
 
Jsp
JspJsp
Jsp
Pooja Verma
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
Vikas Jagtap
 
PHP COOKIES AND SESSIONS
PHP COOKIES AND SESSIONSPHP COOKIES AND SESSIONS
PHP COOKIES AND SESSIONS
Degu8
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
kamal kotecha
 
Servlet lifecycle
Servlet  lifecycleServlet  lifecycle
Servlet lifecycle
chauhankapil
 
Http session (Java)
Http session (Java)Http session (Java)
Http session (Java)
Mrittunjoy Das
 
HTTP request and response
HTTP request and responseHTTP request and response
HTTP request and response
Sahil Agarwal
 
JDBC Driver Types
JDBC Driver TypesJDBC Driver Types
JDBC Driver Types
Rahul Sharma
 
L11 array list
L11 array listL11 array list
L11 array list
teach4uin
 
Enterprise java unit-2_chapter-3
Enterprise  java unit-2_chapter-3Enterprise  java unit-2_chapter-3
Enterprise java unit-2_chapter-3
sandeep54552
 
Http Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responsesHttp Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responses
bharathiv53
 
WEB TECHNOLOGIES JSP
WEB TECHNOLOGIES  JSPWEB TECHNOLOGIES  JSP
WEB TECHNOLOGIES JSP
Jyothishmathi Institute of Technology and Science Karimnagar
 
Replication Techniques for Distributed Database Design
Replication Techniques for Distributed Database DesignReplication Techniques for Distributed Database Design
Replication Techniques for Distributed Database Design
Meghaj Mallick
 
Enterprise java unit-3_chapter-1-jsp
Enterprise  java unit-3_chapter-1-jspEnterprise  java unit-3_chapter-1-jsp
Enterprise java unit-3_chapter-1-jsp
sandeep54552
 
Databind in asp.net
Databind in asp.netDatabind in asp.net
Databind in asp.net
Sireesh K
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packages
vamsi krishna
 
Mining single dimensional boolean association rules from transactional
Mining single dimensional boolean association rules from transactionalMining single dimensional boolean association rules from transactional
Mining single dimensional boolean association rules from transactional
ramya marichamy
 
PHP COOKIES AND SESSIONS
PHP COOKIES AND SESSIONSPHP COOKIES AND SESSIONS
PHP COOKIES AND SESSIONS
Degu8
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
kamal kotecha
 
HTTP request and response
HTTP request and responseHTTP request and response
HTTP request and response
Sahil Agarwal
 
L11 array list
L11 array listL11 array list
L11 array list
teach4uin
 
Enterprise java unit-2_chapter-3
Enterprise  java unit-2_chapter-3Enterprise  java unit-2_chapter-3
Enterprise java unit-2_chapter-3
sandeep54552
 
Http Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responsesHttp Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responses
bharathiv53
 
Replication Techniques for Distributed Database Design
Replication Techniques for Distributed Database DesignReplication Techniques for Distributed Database Design
Replication Techniques for Distributed Database Design
Meghaj Mallick
 

Similar to Wt unit 3 (20)

J2ee servlet
J2ee servletJ2ee servlet
J2ee servlet
vinoth ponnurangam
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
ssbd6985
 
servlets sessions and cookies, jdbc connectivity
servlets sessions and cookies, jdbc connectivityservlets sessions and cookies, jdbc connectivity
servlets sessions and cookies, jdbc connectivity
snehalatha790700
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
Jafar Nesargi
 
Java Servlet
Java ServletJava Servlet
Java Servlet
Yoga Raja
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
deepak kumar
 
SERVLET in web technolgy engineering.pptx
SERVLET in web technolgy engineering.pptxSERVLET in web technolgy engineering.pptx
SERVLET in web technolgy engineering.pptx
ARUNKUMARM230658
 
SERVLETS (2).pptxintroduction to servlet with all servlets
SERVLETS (2).pptxintroduction to servlet with all servletsSERVLETS (2).pptxintroduction to servlet with all servlets
SERVLETS (2).pptxintroduction to servlet with all servlets
RadhikaP41
 
Servlets
ServletsServlets
Servlets
Sasidhar Kothuru
 
Servlets
ServletsServlets
Servlets
Rajkiran Mummadi
 
Servlets-UNIT3and introduction to servlet
Servlets-UNIT3and introduction to servletServlets-UNIT3and introduction to servlet
Servlets-UNIT3and introduction to servlet
RadhikaP41
 
WEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES ServletWEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES Servlet
Jyothishmathi Institute of Technology and Science Karimnagar
 
Unitwwsbdsbsdbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-4.pptx
Unitwwsbdsbsdbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-4.pptxUnitwwsbdsbsdbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-4.pptx
Unitwwsbdsbsdbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-4.pptx
VikasTuwar1
 
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
PRIYADARSINISK
 
J servlets
J servletsJ servlets
J servlets
reddivarihareesh
 
Servlets
ServletsServlets
Servlets
Akshay Ballarpure
 
Adv java unit 4 M.Sc CS.pdf
Adv java unit 4 M.Sc CS.pdfAdv java unit 4 M.Sc CS.pdf
Adv java unit 4 M.Sc CS.pdf
KALAISELVI P
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java Servlet
Fahmi Jafar
 
IP UNIT III PPT.pptx
 IP UNIT III PPT.pptx IP UNIT III PPT.pptx
IP UNIT III PPT.pptx
ssuser92282c
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technology
Minal Maniar
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
ssbd6985
 
servlets sessions and cookies, jdbc connectivity
servlets sessions and cookies, jdbc connectivityservlets sessions and cookies, jdbc connectivity
servlets sessions and cookies, jdbc connectivity
snehalatha790700
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
Jafar Nesargi
 
Java Servlet
Java ServletJava Servlet
Java Servlet
Yoga Raja
 
SERVLET in web technolgy engineering.pptx
SERVLET in web technolgy engineering.pptxSERVLET in web technolgy engineering.pptx
SERVLET in web technolgy engineering.pptx
ARUNKUMARM230658
 
SERVLETS (2).pptxintroduction to servlet with all servlets
SERVLETS (2).pptxintroduction to servlet with all servletsSERVLETS (2).pptxintroduction to servlet with all servlets
SERVLETS (2).pptxintroduction to servlet with all servlets
RadhikaP41
 
Servlets-UNIT3and introduction to servlet
Servlets-UNIT3and introduction to servletServlets-UNIT3and introduction to servlet
Servlets-UNIT3and introduction to servlet
RadhikaP41
 
Unitwwsbdsbsdbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-4.pptx
Unitwwsbdsbsdbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-4.pptxUnitwwsbdsbsdbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-4.pptx
Unitwwsbdsbsdbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-4.pptx
VikasTuwar1
 
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
PRIYADARSINISK
 
Adv java unit 4 M.Sc CS.pdf
Adv java unit 4 M.Sc CS.pdfAdv java unit 4 M.Sc CS.pdf
Adv java unit 4 M.Sc CS.pdf
KALAISELVI P
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java Servlet
Fahmi Jafar
 
IP UNIT III PPT.pptx
 IP UNIT III PPT.pptx IP UNIT III PPT.pptx
IP UNIT III PPT.pptx
ssuser92282c
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technology
Minal Maniar
 
Ad

Recently uploaded (20)

LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
Political History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptxPolitical History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
SPRING FESTIVITIES - UK AND USA -
SPRING FESTIVITIES - UK AND USA            -SPRING FESTIVITIES - UK AND USA            -
SPRING FESTIVITIES - UK AND USA -
Colégio Santa Teresinha
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
Operations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdfOperations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdf
Arab Academy for Science, Technology and Maritime Transport
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
Ad

Wt unit 3

  • 3. Concepts of CGI What is CGI ? The Common Gateway Interface, or CGI, is a set of standards that define how information is exchanged between the web server and a custom script. The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface with information servers such as HTTP servers.
  • 4. Concepts of CGI 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. Concepts of CGI CGI Architecture Diagram
  • 6. Disadvantages of CGI There are many problems in CGI technology: 1. If number of clients increases, it takes more time for sending response. 2. For each request, it starts a process and Web server is limited to start processes. 3. It uses platform dependent language e.g. C, C++, perl.
  • 7. Concepts of Servlets What is a Servlet? Servlet can be described in many ways, depending on the context. •Servlet is a technology i.e. used to create web application. •Servlet is an API that provides many interfaces and classes including documentations. •Servlet is an interface that must be implemented for creating any servlet. •Servlet is a class that extend the capabilities of the servers and respond to the incoming request. It can respond to any type of requests. •Servlet is a web component that is deployed on the server to create dynamic web page.
  • 9. Concepts of Servlets Advantage of Servlet There are many advantages of servlet over CGI. The basic benefits of servlet are as follows: •better performance: because it creates a thread for each request not process. •Portability: because it uses java language. •Robust: Servlets are managed by JVM so we don't need to worry about memory leak, garbage collection etc. •Secure: because it uses java language..
  • 10. Concepts of Servlets Advantage of Servlet The web container creates threads for handling the multiple requests to the servlet. Threads have a lot of benefits over the Processes such as they share a common memory area, lightweight, cost of communication between the threads are low.
  • 11. Concepts of Servlets Life Cycle of a Servlet (Servlet Life Cycle) The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the servlet: Servlet class is loaded. Servlet instance is created. init method is invoked. service method is invoked. destroy method is invoked.
  • 12. Concepts of Servlets Life Cycle of a Servlet (Servlet Life Cycle)
  • 13. Concepts of Servlets Servlet Life Cycle methods The init() Method: The init method is called only once. It is called only when the servlet is created, and not called for any user requests afterwards. The init method definition looks like this − public void init() throws ServletException { // Initialization code... }
  • 14. Concepts of Servlets Servlet Life Cycle methods(cont..) The service() Method The service() method is the main method to perform the actual task. The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers) and to write the formatted response back to the client. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
  • 15. Concepts of Servlets Servlet Life Cycle methods(cont..) The service() Method Here is the signature of this method − public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { ….. … } We have nothing to do with service() method but you override either doGet() or doPost() depending on what type of request you receive from the client.
  • 16. Concepts of Servlets Servlet Life Cycle methods(cont..) The destroy() Method The destroy() method is called only once at the end of the life cycle of a servlet. This method gives your servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities. public void destroy() { // Finalization code... }
  • 17. Concepts of Servlets Servlet Life Cycle Scenario
  • 18. Sample Code of Servlets //Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // Extend HttpServlet class public class HelloWorld extends HttpServlet { private String message; public void init() throws ServletException { // Do required initialization message = "Hello World"; } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType("text/html"); // Actual logic goes here. PrintWriter out = response.getWriter(); out.println("<h1>" + message + "</h1>"); } public void destroy() { // do nothing. } }
  • 19. Compiling Servlets Compiling a Servlet: 1. Let us create a file with name HelloWorld.java with the code shown above. 2. Place this file at C:ServletDevel (in Windows) or at /usr/ServletDevel (in Unix). 3. This path location must be added to CLASSPATH before proceeding further. 4. Assuming your environment is setup properly, go in ServletDevel directory and compile HelloWorld.java as follows − $ javac HelloWorld.java
  • 20. Compiling Servlets(con..) 5. If the servlet depends on any other libraries, you have to include those JAR files on your CLASSPATH as well. 6. Include only servlet-api.jar JAR file because if you are not using any other library in Hello World program. 7. If everything goes fine, above compilation would produce HelloWorld.class file in the same directory. Next section would explain how a compiled servlet would be deployed in production.
  • 21. Servlets Deployment Servlet Deployment: Step 1: By default, A servlet application is located at the path <Tomcat-installationdirectory>/webapps/ROOT and the class file would reside in <Tomcat-installationdirectory>/webapps/ROOT/WEB- INF/classes. If you have a fully qualified class name, of com.myorg.MyServlet then this servlet class must be located in WEB-INF/classes/com/myorg/MyServlet.class.
  • 22. Servlets Deployment(con..) Step 2: let us copy HelloWorld.class into <Tomcat-installationdirectory>/webapps/ROOT/WEB- INF/classes Step 3: create following entries in web.xml file located in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/
  • 24. Servlets Deployment(cont..) Step 4: Start tomcat server using <Tomcat-installationdirectory>binstartup.bat (on Windows) or <Tomcat-installationdirectory>/bin/startup.sh (on Linux/Solaris etc.) and Step 5:finally type http://localhost:8080/HelloWorld in the browser's address box.
  • 25. Servlets Deployment(cont..) Servlet API The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet api. The javax.servlet package contains many interfaces and classes that are used by the servlet or web container. These are not specific to any protocol. The javax.servlet.http package contains interfaces and classes that are responsible for http requests only.
  • 26. Servlets Deployment(cont..) There are many interfaces in javax.servlet package. They are as follows: 1. Servlet 2. ServletRequest 3. ServletResponse 4. RequestDispatcher 5. ServletConfig 6. ServletContext 7. SingleThreadModel 8. Filter 9. FilterConfig 10. FilterChain 11. ServletRequestListener 12. ServletRequestAttributeListener 13. ServletContextListener 14. ServletContextAttributeListener
  • 27. Servlets Deployment(cont..) There are many classes in javax.servlet package. They are as follows: 1. GenericServlet 2. ServletInputStream 3. ServletOutputStream 4. ServletRequestWrapper 5. ServletResponseWrapper 6. ServletRequestEvent 7. ServletContextEvent 8. ServletRequestAttributeEvent 9. ServletContextAttributeEvent 10. ServletException 11. UnavailableException
  • 28. Servlets Deployment(cont..) Interfaces in javax.servlet.http package 1. HttpServletRequest 2. HttpServletResponse 3. HttpSession 4. HttpSessionListener 5. HttpSessionAttributeListener 6. HttpSessionBindingListener 7. HttpSessionActivationListener 8. HttpSessionContext (deprecated now)
  • 29. Servlets Deployment(cont..) Classes in javax.servlet.http package 1. HttpServlet 2. Cookie 3. HttpServletRequestWrapper 4. HttpServletResponseWrapper 5. HttpSessionEvent 6. HttpSessionBindingEvent 7. HttpUtils (deprecated now)
  • 30. Servlets Deployment(cont..) Parameters in Servlets The parameters are the way in which a client or user can send information to the Http Server
  • 31. Servlets Deployment(cont..) Parameters in Servlets For example, in a login screen, we need to send to the server, the user and the password so that it validates them.
  • 32. Servlets Deployment(cont..) Parameters in Servlets For example, How does the client or the Browser send these parameters using the methods GET or POST, The first thing we are going to do is to create in our site a page "login.html" with the following content: <html> <body> <form action="login" method="get"> <table> <tr> <td>User</td> <td><input name="user" /></td> </tr> <tr> <td>password</td> <td><input name="password" /></td> </tr> </table> <input type="submit" /> </form> </body> </html>
  • 33. Servlets Deployment(cont..) Parameters in Servlets Then, we create a Servlet which receives the request in /login , which is the indicated direction in the action attribute of the tag <form> of login.html
  • 34. Servlets Deployment(cont..) import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String user = req.getParameter("user"); String pass = req.getParameter("password"); if ("edu4java".equals(user) && "eli4java".equals(pass)) { response(resp, "login ok"); } else { response(resp, "invalid login"); } }
  • 35. Servlets Deployment(cont..) private void response(HttpServletResponse resp, String msg) throws IOException { PrintWriter out = resp.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<t1>" + msg + "</t1>"); out.println("</body>"); out.println("</html>"); } }
  • 36. Servlets Deployment(cont..) We modify web.xml to link /login with this Servlet. <web-app> <servlet> <servlet-name>timeservlet</servlet-name> <servlet-class>com.edu4java.servlets.FirstServlet</servlet-class> </servlet> <servlet> <servlet-name>login-servlet</servlet-name> <servlet-class>com.edu4java.servlets.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>timeservlet</servlet-name> <url-pattern>/what-time-is-it</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>login-servlet</servlet-name> <url-pattern>/login</url-pattern> </servlet-mapping> </web-app>
  • 37. Servlets Deployment(cont..) Session Tracking and Cookies Session Tracking: Keeping track of a sequence of related requests sent by a client to perform some designated task is known as “Session Tracking” Cookies are one of the solutions to session tracking.
  • 38. Servlets Deployment(cont..) Session Tracking and Cookies(cont..) Cookies: 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.
  • 39. Servlets Deployment(cont..) Session Tracking and Cookies(cont..) How Cookies Work:
  • 40. Servlets Deployment(cont..) Session Tracking and Cookies(cont..) How Cookies Work: •By default, each request is considered as a new request. •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. •we recognize the user as the old user.
  • 41. Servlets Deployment(cont..) Session Tracking and Cookies(cont..) How Cookies Work: •By default, each request is considered as a new request. •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. •we recognize the user as the old user.
  • 42. Servlets Deployment(cont..) Session Tracking and Cookies(cont..) 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.
  • 43. Servlets Deployment(cont..) Session Tracking and Cookies(cont..) Advantage of Cookies Simplest technique of maintaining the state. Cookies are maintained at client side. Disadvantage of Cookies It will not work if cookie is disabled from the browser. Only textual information can be set in Cookie object.
  • 44. Servlets Deployment(cont..) Session Tracking and Cookies(cont..) Cookie class javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of useful methods for cookies.
  • 45. Servlets Deployment(cont..) Session Tracking and Cookies(cont..) Constructor of Cookie class Cookie() : constructs a cookie. Cookie(String name, String value) : constructs a cookie with a specified name and value.
  • 46. Servlets Deployment(cont..) Session Tracking and Cookies(cont..) Method Descriptionpublic 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
  • 47. Servlets Deployment(cont..) Session Tracking and Cookies(cont..) How to send Cookies to the Client( 3 steps ) 1) Create a Cookie object. Cookie c = new Cookie("userName",”Vits"); 2) Set the maximum Age: c.setMaxAge(1800); // value in seconds 3) Place the Cookie in HTTP response header: response.addCookie(c);
  • 48. Servlets Deployment(cont..) Session Tracking and Cookies(cont..) How to Read Cookies from the Client/browser Cookie c[]=request.getCookies(); //c.length gives the cookie count for(int i=0;i<c.length;i++) { out.print("Name: "+c[i].getName()+" & Value: "+c[i].getValue()); }
  • 49. Servlets Deployment(cont..) Session Tracking and Cookies(cont..) How to delete Cookies from the Client/browser If you want to delete a cookie then you simply need to follow up following three steps − Read an already existing cookie and store it in Cookie object. Set cookie age as zero using setMaxAge() method to delete an existing cookie Add this cookie back into response header.
  • 50. Servlets Deployment(cont..) Session Tracking and Cookies(cont..) How to delete Cookies from the Client/browser Let's see the simple code to delete cookie. It is mainly used to logout or sign out the user. Cookie ck=new Cookie("user",""); //deleting value of cookie ck.setMaxAge(0); //changing the maximum age to 0 seconds response.addCookie(ck); //adding cookie in the response
  • 51. Servlets Deployment(cont..) Session Tracking and Cookies(cont..) Http Sessions A session contains information specific to a particular user across the whole application. In such case, container creates a session id for each user. The container uses this id to identify the particular user. This unique ID can be stored into a cookie or in a request parameter. The HttpSession stays alive until it has not been used for more than the timeout value specified in tag in deployment descriptor file. The default timeout value is 30 minutes, this is used if you don’t specify the value in tag.
  • 52. Servlets Deployment(cont..) Session Tracking and Cookies(cont..) Http Sessions(cont..)
  • 53. Servlets Deployment(cont..) Session Tracking and Cookies(cont..) Http Sessions(cont..) This is how you create a HttpSession object. protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { HttpSession session = req.getSession(); }
  • 54. Servlets Deployment(cont..) Http Sessions(cont..) How you can store user information in HttpSession object. setAttribute(): method stores user information session object later when needed this information can be fetched from the session.
  • 55. Servlets Deployment(cont..) Http Sessions(cont..) How you can store user information in HttpSession object. Example: storing username, email-id and user age in session with the attribute name uName, uemailId and uAge respectively. session.setAttribute("uName", "Chaitanya"); session.setAttribute("uemailId", "[email protected]"); session.setAttribute("uAge", "30");
  • 56. Servlets Deployment(cont..) Http Sessions(cont..) TO get the value from session we use the getAttribute() method of HttpSession interface. Example: String userName = (String) session.getAttribute("uName"); String userEmailId = (String) session.getAttribute("uemailId"); String userAge = (String) session.getAttribute("uAge");
  • 57. Servlets Deployment(cont..) Http Sessions(cont..) Sr.No. Method & Description 1 public Object getAttribute(String name) This method returns the object bound with the specified name in this session, or null if no object is bound under the name. 2 public Enumeration getAttributeNames() This method returns an Enumeration of String objects containing the names of all the objects bound to this session. 3 public long getCreationTime() This method returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT. 4 public String getId() This method returns a string containing the unique identifier assigned to this session.
  • 58. Servlets Deployment(cont..) Http Sessions(cont..) Sr.No. Method & Description 5 public long getLastAccessedTime() This method returns the last accessed time of the session, in the format of milliseconds since midnight January 1, 1970 GMT 6 public int getMaxInactiveInterval() This method returns the maximum time interval (seconds), that the servlet container will keep the session open between client accesses. 7 public void invalidate() This method invalidates this session and unbinds any objects bound to it. 8 public boolean isNew() This method returns true if the client does not yet know about the session or if the client chooses not to join the session.
  • 59. Servlets Deployment(cont..) Http Sessions(cont..) Sr.No. Method & Description 9 public void removeAttribute(String name) This method removes the object bound with the specified name from this session. 10 public void setAttribute(String name, Object value) This method binds an object to this session, using the name specified. 11 public void setMaxInactiveInterval(int interval) This method specifies the time, in seconds, between client requests before the servlet container will invalidate this session.