Tom Dawn
Tom Dawn

Reputation: 295

java servlet get cookie value in JSP

In java servlet I have following code:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {       
    Cookie cookie = new Cookie("tom_cookies",Long.toString(new Date().getTime()));
    cookie.setMaxAge(30);
    cookie.setPath(request.getContextPath());
    cookie.setComment("1");
    cookie.setVersion(1);
    System.out.println("Cookie created!");
    response.addCookie(cookie);
}

In JSP index.jsp I have following code:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>MyIndex</title>
</head>
<body>
<div>CookieComment: <%
Cookie[] my = request.getCookies();
for(int i=0;i<my.length;i++){
String comment = my[i].getComment();
out.println(comment);
}
%> 
</div></body></html>

My web.xml:

<?xml version="1.0" encoding="UTF-8"?>

<servlet>
<servlet-name>Test</servlet-name>
<servlet-class>Servlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Test</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>

<display-name>1aaa</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>

In local:8080/servlet, what I expect is like:

CookieComment: 1

However, it only shows:

CookieComment: null

whats wrong here?

Upvotes: 0

Views: 3763

Answers (2)

AlbertoRuvel
AlbertoRuvel

Reputation: 356

You do not really need to get the cookies from the request object via scriptlet code, you can use the implicit variable called 'cookie' via EL

${cookie.yourCookieName}

This should print the value of your cookie in the JSP page. It looks for the cookie in the response object

Hope it helps

Upvotes: 1

Darshan Mehta
Darshan Mehta

Reputation: 30809

This is how cookies work:

  1. Browser sends a request to server.
  2. Server script sends a set of cookies to the browser.
  3. Browser stores this information on local machine for future use.
  4. When next time browser sends any request to web server then it sends those cookies information to the server and server uses that information to identify the user.

What you are trying to do is, access the cookies set in response object (step 2) from request object(step 1). As request object clearly has no idea of the cookie set in response, you are getting null value.

You can only access cookie in the subsequent request sent by browser (please note that although the code between <% and %> is written in html/jsp, it is actually server side code and is executed before response is rendered.

If you want to pass something back from server and print it then you can use response object or set attributes in request.

Upvotes: 1

Related Questions