会话到期时,我需要重定向到登录页面。
我正在使用 HttpSessionListener,它正在调用 sessionDestroyed 方法,但我无法重定向到登录页面。
重定向时出现空指针异常
Java 类
import com.and.web.util.FacesUtils;
import java.io.IOException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class MyHttpSessionListener implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent se) {
HttpSession session = se.getSession();
System.out.print(getTime() + " (session) Created:");
System.out.println("ID=" + session.getId() + " MaxInactiveInterval="
+ session.getMaxInactiveInterval());
}
public void sessionDestroyed(HttpSessionEvent se) {
HttpSession session = se.getSession();
session.invalidate();
try {
FacesUtils.getExternalContext().redirect("/tnt-ui/");
} catch (IOException ex) {
Logger.getLogger(MyHttpSessionListener.class.getName()).log(Level.SEVERE, null, ex);
}
// session has been invalidated and all session data
//(except Id)is no longer available
System.out.println(getTime() + " (session) Destroyed:ID=" + session.getId());
}
private String getTime() {
return new Date(System.currentTimeMillis()).toString();
}
}
Web.xml
<listener>
<listener-class>`com.and.web.bean.MyHttpSessionListener`</listener-class>
</listener>
这该怎么做?请给出解决方案。