A
Cookie is a small piece of data sent from a website and stored in a
user's web browser while the user is browsing that website. Every
time the user loads the website, the browser sends the cookie back to
the server to notify the website of the user's previous activity.
The
HttpServletRequest
interface
provides the getCookies
method
to obtain an array of cookies that are present in the
request.
Main.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <form method="get" action="/servlet/GetCookies"> <input type="submit"> </form> </body> </html>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"> <servlet> <servlet-name>GetCookies</servlet-name> <servlet-class>GetCookies</servlet-class> </servlet> <servlet-mapping> <servlet-name>GetCookies</servlet-name> <url-pattern>/GetCookies</url-pattern> </servlet-mapping> </web-app>
GetCookies.java
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.*; public class GetCookies extends HttpServlet { @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{ try(PrintWriter out = res.getWriter()){ String header = "<html>" + "<head>" + "<title> Hello World </title>" + "</head>" + "<body>" + "<h1> <br />"; String footer = "</h1> </body>" + "</html>"; Cookie[] cookies = req.getCookies(); out.println(header); for(Cookie c : cookies){ out.println(c.getName() + " " + c.getValue()); } out.println(footer); } } }
Sample
Output
No comments:
Post a Comment