0

I have a legacy application using JSF version 1.1

I am trying to set a cookie in all responses, but through a PhaseListener implementation instead of usual Filter because of specific requirement.

I did something like:

public class MyPhaseListener implements PhaseListener {

    public PhaseId getPhaseId() {
        return PhaseId.ANY_PHASE;
    }

    public void beforePhase(PhaseEvent event) {
    }

    public void afterPhase(PhaseEvent event) {
        if (event.getPhaseId() == PhaseId.RENDER_RESPONSE) {
            HttpServletResponse httpResponse = (HttpServletResponse) FacesContext
                            .getCurrentInstance().getExternalContext().getResponse();
            int cookieValue = 100;
            Cookie cookie = new Cookie("myCookie", "" + cookieValue);
            cookie.setPath("/");
            httpResponse.addCookie(cookie);
        }
    }
}

However, when I am checking the responses in chrome dev console, I do not see this cookie.

What am I doing wrong?

Jasper de Vries
  • 19,370
  • 6
  • 64
  • 102
Vicky
  • 16,679
  • 54
  • 139
  • 232
  • Why do you want to do this in a JSF phaselistener and not in a servletfilter like most do? – Kukeltje Feb 03 '19 at 09:58
  • @Kukeltje: I want to set some value in the cookie which is only available after Faces Servlet has executed. Which will only be happening after ServletFilter. – Vicky Feb 03 '19 at 11:18
  • 1
    Just ['chain'](https://stackoverflow.com/questions/4122870/what-is-the-use-of-filter-and-chain-in-servlet) and set the cookie when you get back in the filter – Kukeltje Feb 03 '19 at 11:44
  • @Kukeltje: Sorry for the late response. can you elaborate a bit? Do you mean I set the required value in response, and grab that in filter on the way back, read from response and set as a cookie? – Vicky Feb 07 '19 at 07:09

1 Answers1

0

after RENDER_RESPONSE is probably to late, before RENDER_RESPONSE should work fine.

tandraschko
  • 2,291
  • 13
  • 13
  • Hmmm good catch. Might indeed be the reason Otoh, would have expected an error then something like 'response already comitted' – Kukeltje Feb 04 '19 at 07:56
  • @tandraschko: I tried the same code in beforePhase method. But I still can not see the cookie at the client side. Am I missing something? – Vicky Feb 11 '19 at 01:02
  • I would try after INVOKE_APPLICATION then – tandraschko Feb 14 '19 at 16:12