springmvc interceptor intercepts ajax requests

When using springmvc to intercept requests, you need to implement the HandlerInterceptor interface in spring. Intercepting ordinary requests does not require special processing, but when intercepting ajax requests, it needs to be processed.

 

1. First write a js, use and rewrite the ajax request, if it is an ajax request, add a flag to it and mark the ajax request

$(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. When logging in, verify that if there is no user logged in, check whether it is an Ajax request. If it is, the js in the previous step will process it. If not, it can be processed according to the ordinary request.

 

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		Tourist tourist = (Tourist) request.getSession().getAttribute(Constance.Session.SESSION_TOURIST);
		if (tourist != null) { //The user is not empty, judge whether he has permission
			return true;
		}else{
			//Intercept processing ajax requests
			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{
				//The user is empty, directly return to the login page
				response.sendRedirect("loginUI.do");
			}
			
			return false;
		}
		
		
	}

 

 

 

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326138166&siteId=291194637