Session過期后自動跳轉到登錄頁面的實例代碼
最近做了一個項目其中有需求,要實現自動登錄功能,通過查閱相關資料,打算用session監(jiān)聽來做,下面給大家列出了配置監(jiān)聽器的方法:
1.在項目的web.xml文件中添加如下代碼:
<!--添加Session監(jiān)聽器--> <listener> <listener-class> 監(jiān)聽器路徑 </listener-class> </listener>
2.編寫java類。
public class SessionListener implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent arg0) {
// session創(chuàng)建時執(zhí)行
SimpleDateFormat simpleFormat = new SimpleDateFormat("mm-ss-ms");
String nowtimes = simpleFormat.format(new Date());
User u=null;
//System.out.println("執(zhí)行。。 當前時間:"+nowtimes+"_"+u);
HttpSession ses= arg0.getSession();
String id=ses.getId()+"_"+ses.getCreationTime();
}
public void sessionDestroyed(HttpSessionEvent arg0) {
// session失效時執(zhí)行
SimpleDateFormat simpleFormat = new SimpleDateFormat("mm-ss-ms");
String nowtimes = simpleFormat.format(new Date());
//System.out.println("session失效了。。 結束時間: "+nowtimes);
}
}
配置完成后等session失效后成功進入sessionDestroyed方法,準備進行頁面跳轉操作,突然發(fā)現怎么寫跳轉,愣住了,繼續(xù)上網請教大神,發(fā)現這個監(jiān)聽是做一些后臺統(tǒng)計處理的,無法實現頁面跳轉的功能。
只能放棄這方法了,開始使用過濾器實現
1、web.xml中添加過濾器配置
<filter> <filter-name>sessionFilter</filter-name> <filter-class>com.orchestrall.web.helper.session.SessionFilter</filter-class> </filter> <filter-mapping> <filter-name>sessionFilter</filter-name> <url-pattern>/actions/*</url-pattern> </filter-mapping>
2、新建SessionFilter類,實現Filter接口。
public class SessionFilterimplements Filter {
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
HttpSession session = httpRequest.getSession();
// 登陸url
String loginUrl = httpRequest.getContextPath() + "/admin/login.jsp";
String url = httpRequest.getRequestURI();
String path = url.substring(url.lastIndexOf("/"));
// 超時處理,ajax請求超時設置超時狀態(tài),頁面請求超時則返回提示并重定向
if (path.indexOf(".action") != -1
&& session.getAttribute("LOGIN_SUCCESS") == null) {
// 判斷是否為ajax請求
if (httpRequest.getHeader("x-requested-with") != null
&& httpRequest.getHeader("x-requested-with")
.equalsIgnoreCase("XMLHttpRequest")) {
httpResponse.addHeader("sessionstatus", "timeOut");
httpResponse.addHeader("loginPath", loginUrl);
chain.doFilter(request, response);// 不可少,否則請求會出錯
} else {
String str = "<script language='javascript'>alert('會話過期,請重新登錄');"
+ "window.top.location.href='"
+ loginUrl
+ "';</script>";
response.setContentType("text/html;charset=UTF-8");// 解決中文亂碼
try {
PrintWriter writer = response.getWriter();
writer.write(str);
writer.flush();
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
chain.doFilter(request, response);
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
3、客戶端JS,用于ajax請求session超時
對于jquery
<script type="text/javascript">
$(document).ajaxComplete(function(event, xhr, settings) {
if(xhr.getResponseHeader("sessionstatus")=="timeOut"){
if(xhr.getResponseHeader("loginPath")){
alert("會話過期,請重新登陸!");
window.location.replace(xhr.getResponseHeader("loginPath"));
}else{
alert("請求超時請重新登陸 !");
}
}
});
</script>
對于extjs的ajax請求
Ext.Ajax.on('requestcomplete',checkUserSessionStatus, this);
function checkUserSessionStatus(conn,response,options){
if(response.getResponseHeader("sessionstatus") == 'timeout'){
if(response.getResponseHeader("loginPath")){
alert("會話過期,請重新登陸!");
window.top.location.href = response.getResponseHeader("loginPath");
}else{
alert("請求超時請重新登陸 !");
}
}
}
如果使某個ajax請求不受全局方法的影響,那么可以在使用$.ajax()方法時,將參數中的global設置為false,jquery代碼如下:
$.ajax({
url:"test.html",
global:false//不觸發(fā)全局ajax事件
})
以上所述是小編給大家介紹的Session過期后自動跳轉到登錄頁面的實例代碼,希望對大家有所幫助,如果大家想了解更多內容敬請關注腳本之家網站!
相關文章
SpringDataJPA之Specification復雜查詢實戰(zhàn)
這篇文章主要介紹了SpringDataJPA之Specification復雜查詢實戰(zhàn),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11
Java數據庫連接池之proxool_動力節(jié)點Java學院整理
Proxool是一種Java數據庫連接池技術。方便易用,便于發(fā)現連接泄漏的情況2017-08-08

