You might implement a Servlet filter to monitor the status of your user sessions. This way, you will detect the expired session out of the Managed Bean and the init method won't be called.
This filter might look like:
public class UriFilter implements javax.servlet.Filter {
@Inject SessionController session;
private static final String SIGNON_PAGE_URI = "/myappname/engine/index.xhtml";
private static final String SUBDOMAIN_URI = "/myappname/engine/";
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse)response;
HttpServletRequest req = (HttpServletRequest )request;
String uri = ((HttpServletRequest) request).getRequestURI();
if( !this.authorize(req ) && !(uri.endsWith("/") || uri.endsWith("index.xhtml") || !uri.endsWith(".xhtml")) ){
if(request.getParameter("fileName") != null)
res.sendRedirect(SIGNON_PAGE_URI+"?uri="+uri.substring(SUBDOMAIN_URI.length(), uri.length())+"?fileName="+request.getParameter("fileName"));
else {
res.setHeader("Cache-Control","no-cache, no-store, must-revalidate");
res.setHeader("Pragma","no-cache");
res.setDateHeader("Expires",0);
res.sendRedirect(SIGNON_PAGE_URI+"?faces-redirect=true");
}
} else{
//Desativa o cache do browser
res.setHeader("Cache-Control","no-cache, no-store, must-revalidate");
res.setHeader("Pragma","no-cache");
res.setDateHeader("Expires",0);
//Processa request e response
chain.doFilter( req, res );
}
}
private boolean authorize( HttpServletRequest req ){
boolean authorized = false;
HttpSession session = req.getSession(false);
if(session != null){
if(this.session != null) {
if(this.session.getLogged() != null) {
authorized = true;
}
}
}
return authorized;
}
@Override
public void destroy() {
}
}
The SessionController is the @SessionScoped that track the logged user.
In your web.xml file you have to specify the filter:
<filter>
<filter-name>URI Filter</filter-name>
<filter-class>com.myappname.filter.UriFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>URI Filter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/engine/*</url-pattern>
</filter-mapping>