14 Replies Latest reply: Feb 10, 2012 2:50 PM by 914936 RSS

    Create New Cookie Help

    914936
      Hello,
      I'm using JDev 11.1.1.5 running a project locally on a IWLS. I'm trying to create a new cookie with HttpServletResponse, bellow is my code. I'm getting no errors. Checked Firefox and no cookies are getting created. I also have a method to print out the cookies, and the value of JSESSIONID is the only one to print. Please provide any insight into my issue. Is there a specific phase I should add the cookie ?

      // beforePhase of jspx page
      if (phaseEvent.getPhaseId() == PhaseId.RENDER_RESPONSE) {

      createNewCookie("cityName", "cityValue", (60*60*24*365));

      }

      // create cookie method
      public void createNewCookie(String cookieName, String cookieValue, int cookieMaxAge){

      HttpServletResponse httpServletResponse = (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
      Cookie cookie = new Cookie(cookieName, cookieValue);
      cookie.setMaxAge(cookieMaxAge);
      httpServletResponse.addCookie(cookie);

      }

      Thank You for feedback,
      -DY
        • 1. Re: Create New Cookie Help
          Timo Hahn
          Try setting the path of the cookie
          cookie.setPath("/");
          then you should find it together with the other cookies.

          Timo
          • 2. Re: Create New Cookie Help
            914936
            I appreciate your response. Unfortunately I have tried setting the path to "/" and many other strings with the same lack of cookie creation.
            • 3. Re: Create New Cookie Help
              Timo Hahn
              Well, the code to set the cookie looks OK (and works for me).
              Have you checked in the browser if you find the cookie there?
              How do you try to reed the cookie later?
              Have you checked if cookies are allowed on the browser?

              Timo
              • 4. Re: Create New Cookie Help
                914936
                Have you checked in the browser if you find the cookie there?
                DY: Yes I have checked FF.
                How do you try to reed the cookie later?
                DY: I have two examples i tried to get the cookie.
                public String getCookie(String cookieName){

                HttpServletRequest httpServletRequest = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
                Cookie[] cookies = httpServletRequest.getCookies();
                if (cookies != null) {
                for(int i=0; i<cookies.length; i++){
                System.out.println( cookies.getValue());
                if (cookies[i].getName().equalsIgnoreCase("cookieKey")){
                String cookieValue = cookies[i].getValue();
                }
                }
                }
                }

                public String getCookie(String cookieName){

                FacesContext vFacesContext = FacesContext.getCurrentInstance();
                ExternalContext vExternalContext = vFacesContext.getExternalContext();
                Map vRequestCookieMap = vExternalContext.getRequestCookieMap();
                Cookie vMyCookie = (Cookie)vRequestCookieMap.get(cookieName);
                if (vMyCookie != null)
                {
                return vMyCookie.getValue();
                }
                else
                {
                return null;
                }

                }

                Have you checked if cookies are allowed on the browser?
                DY: Yes cookies is allowed. I set a cookie in Javascript on the same page.
                • 5. Re: Create New Cookie Help
                  Timo Hahn
                  Where do you try to set the cookie?
                  In a bean method or somewhere else (where?)?

                  Timo
                  • 6. Re: Create New Cookie Help
                    Timo Hahn
                    I wrote a small test class which works for me.
                    Class CookieBean:
                    import oracle.adf.share.logging.ADFLogger;
                    
                    
                    public class CookieBean
                    {
                        final static ADFLogger mLogger = ADFLogger.createADFLogger(CookieBean.class);
                    
                        public CookieBean()
                        {
                        }
                    
                        public Cookie getCookie(String cookieName)
                        {
                    
                            HttpServletRequest httpServletRequest =
                                (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
                                .getRequest();
                            Cookie[] cookies = httpServletRequest.getCookies();
                            if (cookies != null)
                            {
                                for (int i = 0; i < cookies.length; i++)
                                {
                    
                                    if (cookies.getName().equalsIgnoreCase(cookieName))
                    {
                    return cookies[i];
                    }
                    }
                    }
                    return null;
                    }

                    public String getCookieVal()
                    {
                    String val = "---";
                    Cookie dum = getCookie("dummCookie");
                    if (dum != null)
                    val = dum.getValue();

                    return val;
                    }

                    public void setupdateCookie(ActionEvent actionEvent)
                    {
                    Cookie dum = getCookie("dummCookie");
                    Date now = new Date();
                    FacesContext facesContext = FacesContext.getCurrentInstance();
                    ExternalContext ectx = facesContext.getExternalContext();
                    HttpServletResponse response = (HttpServletResponse) ectx.getResponse();
                    if (dum == null)
                    {
                    // erstellen des Cookie jupp
                    dum = new Cookie("dummCookie", "dum-" + now.toString() + "-dum");
                    dum.setMaxAge(10 * 60);
                    dum.setPath("/");

                    response.addCookie(dum);
                    mLogger.info("Create cookie: " + dum.getValue());
                    }
                    else
                    {
                    dum.setValue("dum-" + now.toString() + "-dum");
                    dum.setPath("/");
                    dum.setMaxAge(10 * 60);
                    response.addCookie(dum);
                    mLogger.info("Update cookie: " + dum.getValue());
                    }
                    }
                    }
                    and a jspx page:
                    <?xml version='1.0' encoding='UTF-8'?>
                    <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1"
                    xmlns:f="http://java.sun.com/jsf/core" xmlns:af="http://xmlns.oracle.com/adf/faces/rich">
                    <jsp:directive.page contentType="text/html;charset=UTF-8"/>
                    <f:view>
                    <af:document title="CookieTest.jspx" id="d1">
                    <af:form id="f1">
                    <af:panelStretchLayout topHeight="50px" id="psl1">
                    <f:facet name="top">
                    <af:outputText value="Cookie Test" id="ot1"
                    inlineStyle="font-size:xx-large;"/>
                    </f:facet>
                    <f:facet name="center">
                    <af:panelGroupLayout layout="scroll" id="pgl1">
                    <af:outputText value="Cookie: #{CookieBean.cookieVal}" id="ot2"
                    partialTriggers="cb1"/>
                    <af:commandButton text="Set or Update Cookie" id="cb1"
                    actionListener="#{CookieBean.setupdateCookie}"/>
                    </af:panelGroupLayout>
                    <!-- id="af_one_column_header_stretched" -->
                    </f:facet>
                    </af:panelStretchLayout>
                    </af:form>
                    </af:document>
                    </f:view>
                    </jsp:root>
                    The bean is registered in request scope. Just hit the button and you should see the cookie value. You need to hit twice the first time as the cookie in not available the first time.
                    
                    Timo                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
                    • 7. Re: Create New Cookie Help
                      914936
                      I'm setting the cookie in a bean that's called from the views beforePhase. See below:

                      // jspx page
                      <f:view beforePhase="#{siteTasks.loadCity}">

                      // bean
                      public void loadCity(PhaseEvent phaseEvent) {
                      if (phaseEvent.getPhaseId() == PhaseId.RENDER_RESPONSE) {
                      createNewCookie("cityName", "cityValue", (60*60*24*365));

                      }
                      }

                      The only difference i see between yours and mine, is that your calling method from a button click and I'm calling mine on page load.
                      • 8. Re: Create New Cookie Help
                        vinod_t_krishnan
                        may be you can try creating the cookie in the getter of the last component bounded to the bean.. like
                        <af:outputText bindings="#{Bean.dummyMethod}" visible="false" />
                        have the above component as the last component in ur page.. and then in the getter of this binding call the createCookie method
                        • 9. Re: Create New Cookie Help
                          914936
                          I appreciate the response. That was a good idea but still so luck. Below is me trying out your idea. The code is ran error free but no cookie added.

                          <af:outputText id="ot2" binding="#{siteTasks.cookieGetter}" visible="false"/>

                          public RichOutputText getCookieGetter() {
                          createNewCookie("cityName", "cityValue", (60*60*24*365));
                          return cookieGetter;
                          }

                          We are using [Pretty Faces|http://ocpsoft.com/prettyfaces/] with are project. I'm starting to think Pretty Faces is blocking the cookie. I will post a thread on their forum. Does anyone have experience using cookies with Pretty Faces?
                          • 10. Re: Create New Cookie Help
                            Timo Hahn
                            The problem seams to be the point of time you try to set the cookie. It looks like the response already contains some data so that you cna't set the cookie in the phase listener. The same is true for the solution with the hidden button. My solution is working because the button action starts a new response and at this point you can add cookies. For more info on this check this http://pdf.coreservlets.com/Cookies.pdf

                            Can't you use a button to set the cookie?
                            You did not provide any use case so it's hard to suggest something.

                            Timo
                            • 11. Re: Create New Cookie Help
                              914936
                              Setting the cookie using a button is also not working.
                              • 12. Re: Create New Cookie Help
                                in the line of fire
                                in 11.1.1.5 i tried it a couple of times and it didnt work
                                • 13. Re: Create New Cookie Help
                                  Timo Hahn
                                  @in the line of fire: You did test what? I provided my test code which worked for me.

                                  Timo
                                  • 14. Re: Create New Cookie Help
                                    914936
                                    Thank you Timo as you have solved my problem. Setting the cookie on button click or in my case a drop down selection is working. My post earlier stating it wasn't working on button click was because my path was set incorrectly. Still not sure why we cant set the cookie on page load, but event listener works and has solved the problem.