Cookies in servlet

590 views 10 slides May 05, 2020
Slide 1
Slide 1 of 10
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10

About This Presentation

Description of cookies in servlet and example


Slide Content

Cookies in Servlet
Prof. Neeraj Bhargava
Kapil Chauhan
Department of Computer Science
School of Engineering & Systems Sciences
MDS University, Ajmer

Cookies in Servlet
Acookieis 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.

Cont..
There are three steps involved in identifying returning
users −
Server script sends a set of cookies to the browser. For
example name, age, or identification number etc.
Browser stores this information on local machine for
future use.
When next time browser sends any request to web
server then it sends those cookies information to the
server and server uses that information to identify the
user.

Types of Cookie
There are 2 types of cookies in servlets.
Non-persistent cookie
Persistent cookie

Cont…
Non-persistent cookie
It isvalid for single sessiononly. It is removed each
time when user closes the browser.
Persistent cookie
It isvalid for multiple session. It is not removed
each time when user closes the browser. It is removed
only if user logout or signout.

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.

Example
public class FirstServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
 try{
 response.setContentType("text/html");
 PrintWriter out = response.getWriter();

 String n=request.getParameter("userName");
 out.print("Welcome "+n);
 Cookie ck=new Cookie("u",n);
 response.addCookie(ck);

 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);}
 }
 }

Assignment
Explain cookies in java script with suitable example.
Tags