How can I handle cookies from a Tag?
1 posts in topic
Flat View  Flat View

Posted By:   Giancarlo_Gallardo
Posted On:   Friday, June 14, 2002 08:24 AM

When I write code inside the doStartTag() method, I can only manage a ServletRequest object when I get it from the pageContext.getRequest() method.

But I need a reference to the HttpServletRequest Object since I want to manage Cookies in the tag.

please any sugestion?

Re: How can I handle cookies from a Tag?

Posted By:   Luigi_Viggiano  
Posted On:   Friday, June 14, 2002 09:01 AM

A Cast should be enough. I've made some code for you:

File: Jsp0.jsp

response.addCookie(new Cookie("test", "value of test"));
response.sendRedirect(request.getContextPath() + "/Jsp1.jsp");

File: Jsp1.jsp

<%@ taglib uri="/WEB-INF/taglib.tld" prefix="test" %>

File: taglib.tld

My first Tag library

A Cookie Display Tag


import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;

public class CookieTag extends javax.servlet.jsp.tagext.TagSupport {

public int doStartTag() throws JspException {
ServletRequest request = pageContext.getRequest();
HttpServletRequest httpRequest = (HttpServletRequest)request;
JspWriter out = pageContext.getOut();

Cookie[] cookies = httpRequest.getCookies();
for (int i = 0; i < cookies.length ; i++) {
Cookie cookie = cookies[i];
String name = cookie.getName();
String value = cookie.getValue();
try {
Cookie name = "+ name +", value = " + value);
} catch ( ioEx) {
throw new JspException(ioEx.getMessage());
return SKIP_BODY;


If you need help to deploy this example let me know.

Jsp0.jsp sets the cookie, then forwads to Jsp1 that displays it. Running this demo (pointing your browser to Jsp0.jsp) you'll get an output like this:

Cookie name = JSESSIONID, value = 64vrqtot61
Cookie name = test, value = value of test

Also the session identifier cookie is displayed ;-)

Have fun,


About | Sitemap | Contact