shiro 拦截器实现session过期拦截ajax请求的处理

拦截器代码:

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("

"+ data[i].menuName + "

"
); } }); }

shiro配置:
需要把session拦截器放在登录拦截器前面
shiro 拦截器实现session过期拦截ajax请求的处理_第1张图片

你可能感兴趣的:(shiro)