2 Answers

0 votes
Setting cookies with servlet involves three steps:

1) Creating a Cookie object: You call the Cookie constructor with a cookie name and a cookie value, both of which are strings.

               Cookie cookie = new Cookie("key","value");

 2) Setting the maximum age: You use setMaxAge to specify how long (in seconds) the cookie should be valid. Following would set up a cookie for 24 hours.


3) Sending the Cookie into the HTTP response headers: You use response.addCookie to add cookies in the HTTP response header as follows:

answered Jun 30, 2016 by Nani
0 votes
  1. Cookie ck=new Cookie("user","sonoo jaiswal");//creating cookie object  
  2. response.addCookie(ck);//adding cookie in the response  
answered Jan 30, 2017 by muneshs16

Related questions

How to read a cookie using servlet?

To read cookies, you need to create an array of javax.servlet.http.Cookie objects by calling the getCookies( ) method of HttpServletRequest. Then cycle through the array,...

java, servlet, jdbc 2 Answer 63 views asked Jun 30, 2016 in Java by Nani

How to delete a cookie using servlet?

There is no direct method offered by servlet API to delete a cookie on server side.Loop through the cookies in the request object to locate the one that you want to delete.for (Cookie cookie:...

java, servlet, jdbc 2 Answer 140 views asked Jun 30, 2016 in Java by Naveen