springmvc拦截器拦截ajax请求

使用springmvc 拦截请求时,需要实现 spring中的HandlerInterceptor这个接口。拦截普通的请求,不需要特殊的处理,但是拦截ajax请求时,则需要处理,

1、首先写一个js,用与复写ajax请求,如果是ajax请求,给其加一个标志,标注释ajax请求

$(function() {
	overrideJQeuryAjax();
});
function overrideJQeuryAjax() {
	var oriAjax = jQuery.ajax;
	// Override jquery ajax to check if session is valid.
	jQuery.ajax = function(options) {
		if (!options.data) {
			options.data = "";
		}
		if (typeof options.data == "string") {
			options.data = options.data + "&_isAjax=true";
		} else {
			options.data._isAjax = true;
		}

		var oriSuccess = options.success;
		if (typeof oriSuccess == 'function') {
			options.success = function(result) {
				if (!checkSession(result)) {
					return false;
				}
				oriSuccess(result);
			}
		}

		var oriError = options.error;
		if (typeof oriError == 'function') {
			options.error = function(result) {
				if (!checkSession(result)) {
					return false;
				}
				window.location = 'error.do';
			}
		}

		oriAjax(options);
	};
}

function checkSession(result) {
	if (typeof result.checkUserAjaxMsg == 'boolean' && !result.checkUserAjaxMsg) {
		window.location = 'loginUI.do';
		return false;
	}
	return true;
}

2、登录时,验证如果没有用户登录,则看看是不是ajax请求,如果是,上一步的js,会做处理,如果不是,则按照普通的请求处理即可

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		Tourist tourist = (Tourist) request.getSession().getAttribute(Constance.Session.SESSION_TOURIST);
		if (tourist != null) { //用户不为空,判断是否有权限
			return true;
		}else{
			//拦截处理 ajax 请求
			String isAjax = request.getParameter("_isAjax");
			if (Boolean.parseBoolean(isAjax)) {
				String message = "{\"checkUserAjaxMsg\":false}";
				response.setContentType("application/json;charset=UTF-8");
				response.getOutputStream().write(message.getBytes());
			}else{
				//用户为空,直接返回登录页面
				response.sendRedirect("loginUI.do");
			}
			
			return false;
		}
		
		
	}

猜你喜欢

转载自1960370817.iteye.com/blog/2404125