0

I'm using a Glassfish 4 server with a JSF2 framework.

My problem

When calling the response.sendRedirect method, I'm having a IllegalStateException.

I don't have a single clue why this exception was raised.

The context

For every xhtml page, I have this method called to check if the user is still logged in.

<body id="body" onload="#{utilisateurBean.isUserLoggedIn()}">

The method

public void isUserLoggedIn() throws IOException {
    if(this.user == null){
        HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
        response.sendRedirect("Project/accueil/index.xhtml");
    }
}

Exception

Infos:   Exception when handling error trying to reset the response.
java.lang.IllegalStateException

Or

Avertissement:   Servlet.service() for servlet session.AppExceptionHandler threw exception
java.lang.IllegalStateException: Cannot forward after response has been committed

I don't know why the response is being commited.

Thank for your help :)

Nordine
  • 824
  • 7
  • 25

2 Answers2

1

You cannot alter the response when the response is already commit/defined.

Here you are displaying the page, so your response is already defined.

You have to do it in another way like showing an error message saying user is not connected and ask user to login again.

You could also do the redirect using javascript.

TheCodeKiller
  • 1,733
  • 2
  • 12
  • 18
  • Thank you, I fixed my problem. I don't why but removing the CSS inside the style tag (in the head tag) did the trick. – Nordine Oct 26 '17 at 15:25
1

Change your code with below snippet:

public void isUserLoggedIn() throws IOException {
if(this.user == null){
    HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
    response.sendRedirect("Project/accueil/index.xhtml");
    return;
 }
}

OR add a check to verify whether response is committed.

response.isCommitted()

For more info related to response already committed, check this.

Rohit Gaikwad
  • 3,677
  • 3
  • 17
  • 40
  • Thank you for your answer. My problem came from writting CSS inside the head tag. Removing it fixed the problem – Nordine Oct 26 '17 at 15:27