攔截器代碼:
package com.xlqh.outlook.shirofilter;import java.io.IOException;import org.apache.shiro.web.filter.PathMatchingFilter;import com.xlqh.outlook.MyShiroConstants.MyShiroConstants;import com.xlqh.outlook.SessionManagement.SessionManagement;import com.xlqh.outlook.entity.yuuser;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;//自訂攔截器,Session到期AJAX處理public class SessionExpiredFilter extends PathMatchingFilter { @Override protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception { yuuser sys = (yuuser) SessionManagement.getSession(MyShiroConstants.Session_USER); if(sys==null){ System.out.println("session到期"); if ("XMLHttpRequest".equalsIgnoreCase(((HttpServletRequest) request).getHeader("X-Requested-With"))) { //ajax的sesson處理 //返回狀態代碼 onLoginFail(response); return false; } else{ //普通的處理,直接給到下一個攔截器 return true; } } return true; } //session到期給403狀態代碼 private void onLoginFail(ServletResponse response) throws IOException { HttpServletResponse httpResponse = (HttpServletResponse) response; httpResponse.setStatus(403); httpResponse.getWriter().write("session逾時了"); }}
前台頁面全域需要處理的,基於jquery的ajax請求都會被攔截
全域的js片段:
var timeoutlogin="/login?code=22"; $.ajaxSetup({ contentType : "application/x-www-form-urlencoded;charset=utf-8", cache : false, complete : function(data, TS) { //對返回的資料data做判斷 debugger; //403是後台攔截器那兒定義的, if (data.status == 403) { //session到期的話,就location到一個頁面 location.href=timeoutlogin; return; } } });
ajax請求的js:
function test() { var valusid = $("#select2").val(); $.post("yurole/selectuserrole", {"userid" : valusid}, function(data) { $("#div2").html(""); debugger; for ( var i = 0; i < data.length; i++) { $("#div2").append("<p><a href='"+data[i].menuUlr+"' target='content' >"+ data[i].menuName + "<a/></p>"); } }); }
shiro配置:
需要把session攔截器放在登入攔截器前面