04.06.2017 Views

servlets_tutorial

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Java Servlets<br />

}<br />

}<br />

Compile above servlet ReadCookies and create appropriate entry in web.xml file. If you<br />

would have set first_name cookie as "John" and last_name cookie as "Player" then<br />

running http://localhost:8080/ReadCookies would display the following result:<br />

Found Cookies Name and Value<br />

Name : first_name, Value: John<br />

Name : last_name, Value: Player<br />

Delete Cookies with Servlet<br />

To delete cookies is very simple. If you want to delete a cookie then you simply need to<br />

follow up following three steps:<br />

<br />

<br />

<br />

Read an already existing cookie and store it in Cookie object.<br />

Set cookie age as zero using setMaxAge() method to delete an existing cookie.<br />

Add this cookie back into response header.<br />

Example<br />

The ollowing example would delete and existing cookie named "first_name" and when<br />

you would run ReadCookies servlet next time it would return null value for first_name.<br />

// Import required java libraries<br />

import java.io.*;<br />

import javax.servlet.*;<br />

import javax.servlet.http.*;<br />

// Extend HttpServlet class<br />

public class DeleteCookies extends HttpServlet {<br />

public void doGet(HttpServletRequest request,<br />

HttpServletResponse response)<br />

throws ServletException, IOException<br />

{<br />

Cookie cookie = null;<br />

Cookie[] cookies = null;<br />

58

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!