Example & Tutorial understanding programming in easy ways.

What are cookies?

A web container can assign a unique session ID as a cookie to each web client and for subsequent requests coming from the client they can be recognized using the recieved cookie over the server to personalize response based on your choice or to keep track of session

Java Cookie Example

For example You can write cookies using the HttpServletResponse object like this:

Cookie cookie = new Cookie("myCookie", "myCookieValue");

response.addCookie(cookie);

How to delete Cookie?

An Example to delete cookie. It is mainly used to logout or signout 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  

An example for showing How to get Cookies?

Simple code to get all the cookies.

    Cookie cke[]=request.getCookies();  
    for(int i=0;i<cke.length;i++){  
     out.print("<br>"+cke[i].getName()+" "+cke[i].getValue());//printing name and value of cookie  
    }  

Read More →