1、首選創建一個繼承HandlerInterceptor的攔截器
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
/**
* 攔截器
*/
public class MyInterceptor implements HandlerInterceptor{
//在請求處理之前進行調用(Controller方法調用之前
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
HttpSession session = httpServletRequest.getSession();
String user = (String) session.getAttribute("user"); //獲取登錄的session信息
if(user!=null){
return true;
}
else{
httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/login/index"); //未登錄自動跳轉界面
return false;
}
}
//請求處理之后進行調用,但是在視圖被渲染之前(Controller方法調用之后)
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle被調用\n");
}
//在整個請求結束之后被調用,也就是在DispatcherServlet 渲染了對應的視圖之后執行(主要是用於進行資源清理工作)
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
System.out.println("afterCompletion被調用\n");
}
}
2、繼承WebMvcConfigureAdapter類,覆蓋其addInterceptors接口,注冊自定義的攔截器:
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
/**
* 注冊攔截器
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
//addPathPattern后跟攔截地址,excludePathPatterns后跟排除攔截地址
registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**").excludePathPatterns("/login/index").excludePathPatterns("/login/login");
}
}
這樣我們就可以在用戶請求到達controller層實現登錄攔截了,所有用戶請求都會被攔截,在prehandle方法進行登錄判斷,返回true則驗證通過,否則失敗
