Read Cookies from Servlet
This section illustrates you how to read cookies from Servlets.
The Cookie Class provides an easy way to read Cookies. You can use getCookies()
method to retrieve all the cookies in your servlet program.
This getCookies() method returns an array of cookie
objects. In this example we will show you how you can retrieve all the cookies
and display using servlets.
Here is the code of ReadCookies.java
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ReadCookies extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException {
Cookie cookie = null;
Cookie[] cookies = request.getCookies();
boolean newCookie = false;
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
if (cookies[i].getName().equals("Cookies")) {
cookie = cookies[i];
}
}
}
if (cookie == null) {
newCookie = true;
int maxAge;
try {
maxAge = new Integer(getServletContext()
.getInitParameter("cookie-age")) .intValue();
}
catch (Exception e) {
maxAge = -1;
}
cookie = new Cookie("Cookies", "" + getNextCookieValue());
cookie.setPath(request.getContextPath());
cookie.setMaxAge(100);
response.addCookie(cookie);
}
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Read Cookie</title>");
out.println("</head>");
out.println("<body>");
out.println
("<h2> Our Cookie named \"Cookies\"information</h2>");
out.println("Cookie value: " + cookie.getValue() + "<br>");
if (newCookie) {
out.println
("Cookie Max-Age: " + cookie.getMaxAge() + "<br>");
out.println("Cookie Path: " + cookie.getPath() + "<br>");
}
out.println("</body>");
out.println("</html>");
out.close();
}
private long getNextCookieValue() {
return new java.util.Date().getTime();
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException {
doGet(request, response);
}
} |
web.xml for ReadCookie.java
<context-param>
<param-name>maxAge</param-name>
<param-value>100</param-value>
</context-param>
<servlet>
<servlet-name>ReadCookies</servlet-name>
<servlet-class>ReadCookies</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ReadCookies</servlet-name>
<url-pattern>/ReadCookies</url-pattern>
</servlet-mapping>
|
After Calling the request, cookie value, cookie maxAge, cookie path along
with cookie name, will be displayed on the browser. And after reloading Cookie
value has been changed with getNextCookieValue() method.
Output will be displayed as:
After reloading the application cookie value will be changed, output will be:
Download Source Code