spring攔截器

蛙蚊丶丶發表於2020-09-30
package com.swjd.interceptor.interceptors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.swjd.interceptor.entity.User;

// 攔截器使用的場景
// 1.攔截判斷會話狀態:session
// 2.判斷許可權操作
// 3.對日誌進行收集

// 使用攔截器必須是實現
public class LoginInterceptor implements HandlerInterceptor{

	// afterCompletion攔截器的preHandle,postHandle方法執行完成之後,做業務的回撥
	// 類似finally的使用
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		User user = (User)request.getSession().getAttribute("use");
		System.out.println("當前賬號:"+user.getName());
		System.out.println("當前訪問地址:"+request.getRequestURI());
	}
	
	// postHandle在預處理方法通過後,則進行進一步業務攔截
	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}
	
	// preHandle預處理方法,主要針對攔截進入業務控制器的請求,做前置業務引導
	// 這個方法的返回值直接影響後續方法是否繼續攔截做業務操作
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		User user = (User)request.getSession().getAttribute("user");
		// 如果會話狀態中有當前物件,則通過本次攔截
		if (user != null) {
			return true;
		}
		// 如果會話狀態異常,攔截請求,到登入頁面
		request.setAttribute("msg", "<script>alert('去登入')</script>");
		request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
		return false;
	}
	
}

相關文章