I need to know how to keep password in cookies.

From a tutorial I have:

For example, to create a cookie named userID with a value a1234, you would use the following.

Cookie c = new Cookie("userID", "a1234");


If you create a cookie and send it to the browser, by default it is a session-level cookie: a cookie that is stored in the browser's memory and deleted when the user quits the browser. If you want the browser to store the cookie on disk, use setMaxAge with a time in seconds, as below.

c.setMaxAge(60*60*24*7); // One week


To send the cookie, insert it into a Set-Cookie HTTP response header by means of the addCookie method of HttpServletResponse

Cookie userCookie = new Cookie("user", "uid1234");
userCookie.setMaxAge(60*60*24*365); // Store cookie for 1 year
response.addCookie(userCookie);

To send a cookie to the client, you create a Cookie, set its maximum age (usually), then use addCookie to send a Set-Cookie HTTP response header. To read the cookies that come back from the client, you should perform the following two tasks, which are summarized below and then described in more detail in the following subsections.

Call request.getCookies. This yields an array of Cookie objects.

Loop down the array, calling getName on each one until you find the cookie of interest. You then typically call getValue and use the value in some application-specific way.

String cookieName = "userID";
Cookie[] cookies = request.getCookies();
if (cookies != null) {
  for(int i=0; i<cookies.length; i++) {
    Cookie cookie = cookies[i];
    if (cookieName.equals(cookie.getName())) {
      doSomethingWith(cookie.getValue());
    }
  }
}

Don't put password as plain text in cookies. Use JCE API to encrypt the password.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.