0
(SOLVED) Error redirecting to a jsf page within a Managerbean. I have an application in Java EE, and I want to validate inside the Loginbean constructor (Viewscope) to redirect to my main page if there is already an open and valid session for that browser.
I can recover the session, I check if it is valid successfully, but I can’t redirect before opening the login screen.
The following error is returned:
Cannot call sendRedirect() after the response has been committed
Bean code
@ManagedBean
@ViewScoped
public class LoginBean implements Serializable {
private static final long serialVersionUID = 3654371476703737165L;
public String testarSessaoLogada() throws IOException {
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
HttpSession session = request.getSession(true);
LoginControle loginControle = (LoginControle) session.getAttribute("loginControle");
if (loginControle.getControleSessaoBean() != null && session != null) {
SessaoLogada sessaoLogada = loginControle.getControleSessaoBean().buscarSessaoLogada(session.getId());
if (sessaoLogada != null) {
if (sessaoLogada.getUsuario().getTipo().equals("Cliente")) {
FuncoesUtils.redirect("");
} else {
try {
FacesContext.getCurrentInstance().getExternalContext().redirect("privado/controle.jsf");
} catch (Exception e) {
try {
FacesContext.getCurrentInstance().getExternalContext().redirect("privado/controle.jsf");
} catch (IOException ex) {
Logger.getLogger(LoginBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
return "";
}
}
On the login.html page you have the following code that has the functionality to load the function that tests whether there is already a logged in session for that browser...
The error occurs precisely when trying to redirect
FacesContext.getCurrentInstance().getExternalContext().redirect("privado/controle.jsf");
I needed to discover the error or even a hint to make this redirection otherwise.... Thank you very much.
Resolution:
https://stackoverflow.com/questions/8399045/conditional-redirection-in-jsf
Just instead of loading the function on a screen component I loaded it on before h:body.
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
...
</h:head>
<f:event type="preRenderView" listener="#{loginBean.testarSessaoLogada()}" />
<h:body>
...
Thanks to all who helped me...
thanks for the @Otávio reply , but the problem that wanted to call this action when rendering the page, I tried to put the same function in the constructor...but the error also persisted... the goal is to check before loading the login, check if there is a logged-in session in the browser and redirect to the control page. Then I only load the login if there is no logged in session in the browser.
– João Paulo