Olá :eek:
Sou novata em JSF e preciso do conselho dos + experientes.
No sistema que estou tratando, ocorre a seguinte situação: o usuário possui uma sessão de 30 minutos. Após este período de “inatividade”, os objetos ManagedBean que estavam na sessão expiram. Então, qdo o usuário tenta continuar a navegação, uma página de erro é exibida, descrevendo o erro: o ManagedBean ‘X’ não foi encontrado…
Quero tratar este erro de forma que, quando a sessão expirar, o usuário, ao tentar navegar, seja redirecionado para a página de login.
A dúvida é: Como devo fazer isso? Usando Filtro? PhaseListener?
Qual é a maneira correta?
Abraços!
Utilize filtro, é uma boa
olha ai um codigo que redireciona o usuário apos a sessão ter expirado
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* When the session destroyed, MySessionListener will do necessary logout
* operations. Later, at the first request of client, this filter will be fired
* and redirect the user to the appropriate timeout page if the session is not
* valid.
*
* Thanks to hturksoy
*
*/
public class SessionTimeoutFilter implements Filter {
// This should be your default Home or Login page
// "login.seam" if you use Jboss Seam otherwise "login.jsf" / "login.xhtml"
// or whatever
private String timeoutPage = "index.jsf";
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException,
ServletException {
if ((request instanceof HttpServletRequest)
&& (response instanceof HttpServletResponse)) {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
// is session expire control required for this request?
if (isSessionControlRequiredForThisResource(httpServletRequest)) {
// is session invalid?
if (isSessionInvalid(httpServletRequest)) {
String timeoutUrl = httpServletRequest.getContextPath()
+ "/" + getTimeoutPage();
System.out
.println("Session is invalid! redirecting to timeoutpage : "
+ timeoutUrl);
httpServletResponse.sendRedirect(timeoutUrl);
return;
}
}
}
filterChain.doFilter(request, response);
}
/*
* session shouldn’t be checked for some pages. For example: for timeout
* page.. Since we’re redirecting to timeout page from this filter, if we
* don’t disable session control for it, filter will again redirect to it
* and this will be result with an infinite loop…
*/
private boolean isSessionControlRequiredForThisResource(
HttpServletRequest httpServletRequest) {
String requestPath = httpServletRequest.getRequestURI();
boolean controlRequired = !org.apache.commons.lang.StringUtils
.contains(requestPath, getTimeoutPage());
return controlRequired;
}
private boolean isSessionInvalid(HttpServletRequest httpServletRequest) {
boolean sessionInValid = (httpServletRequest.getRequestedSessionId() != null)
&& !httpServletRequest.isRequestedSessionIdValid();
return sessionInValid;
}
public void destroy() {
}
public String getTimeoutPage() {
return timeoutPage;
}
public void setTimeoutPage(String timeoutPage) {
this.timeoutPage = timeoutPage;
}
}
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class SessionListener implements HttpSessionListener {
public SessionListener() {}
public void sessionCreated(HttpSessionEvent event) {}
public void sessionDestroyed(HttpSessionEvent event) {
// get the destroying session…
HttpSession session = event.getSession();
/*
* nobody can reach user data after this point because session is invalidated already.
* So, get the user data from session and save its logout information
* before losing it.
* User’s redirection to the timeout page will be handled by the SessionTimeoutFilter.
*/
// Only if needed
try {
prepareLogoutInfoAndLogoutActiveUser(session);
} catch(Exception e) {
System.out.println("Error while logging out at session destroyed: " + e.getMessage());
}
}
/**
* Clean your logout operations.
*/
public void prepareLogoutInfoAndLogoutActiveUser(HttpSession httpSession) {
// Only if needed
}
}
web.xml
<listener>
<listener-class>
seu_pacote.SessionListener
</listener-class>
</listener>
<filter>
<filter-name>SessionTimeoutFilter</filter-name>
<filter-class>
seu_pacote.SessionTimeoutFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>SessionTimeoutFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Att. Dirceu