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

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?
regards,
gianca.

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




1.0
1.1
test
My first Tag library

cookieTag
CookieTag
empty
A Cookie Display Tag




File: CookieTag.java

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 {
out.print("
Cookie name = "+ name +", value = " + value);
} catch (java.io.IOException 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,

~Luigi.

About | Sitemap | Contact