1. 本文目的
- 认识
Spring
中的拦截器HandlerInterceptor
; - 一个登录拦截示例;
2. HandlerInterceptor
主要有三个方法:
preHandle
: 进入controller
之前;postHandle
:controller
执行后,还未进行页面渲染,可以修改ModelAndView
;afterCompletion
:页面已经渲染,整个请求完了。
返回的都是布尔值,true
代表放行,false
代表阻止。
3. 登录拦截示例
3.1 LoginHandlerInterceptor
- 实现
HandlerInterceptor
接口; - 在
preHandle
方法中验证Session
;
package com.road.web.filter;
import com.road.core.vo.Constant;
import com.road.core.vo.UserSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
@Slf4j
public class LoginHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response
, Object handler) throws Exception {
//获取请求地址
String url =request.getRequestURL().toString();
//打印拦截的url
log.info("「LoginHandlerInterceptor」- url: {}", url);
//获取Session
HttpSession session = request.getSession();
//从Session中获取UserSession
UserSession userSession = (UserSession) session.getAttribute(Constant.USER_SESSION);
//如果UserSession为空,则未登录
if(userSession == null){
// 在配置 excludePathPatterns 时,别忘了斜杠 / ,否则循环调用此方法导致栈溢出:StackOverflowError: null
request.getRequestDispatcher("/login").forward(request, response);
return false; //必须加上,否则报错:Cannot forward after response has been committed
}
//如果UserSession不为空,放行
return true;
}
}
3.2 配置自定义拦截器
- 自定义配置类继承
WebMvcConfigurationSupport
; - 重写
addInterceptors
方法,添加拦截器
package com.road.config;
import com.road.web.filter.LoginHandlerInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
@Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor()).excludePathPatterns("/login");
}
}