大家好,我是执梗。本专栏将从Spring
入门开始讲起,详细讲解各类配置的使用以及原因,到使用SpringBoot
进行开发实战,旨在记录学习生活的同时也希望能帮到大家,如果对您能有所帮助,还望能点赞关注该专栏,对于专栏内容有错还望您可以及时指点,非常感谢大家 🌹。
在本专栏上文中,我们讲解了AOP
,在用户验证登陆功能上,可以利用它来进行统一,但使用它却有两个很大的缺点:
HttpSession
对象为了解决上述问题,Spring
中为我们准备了拦截器:HandlerInterceptor
。
拦截器的实现,主要分成两个步骤:
HandlerInterceptor
并重写方法preHandle
,这个方法会在执行所有方法之前预先执行。import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;/** 自定义重写拦截器* */
@Component
public class LoginIntercept implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {//1.得到session对象HttpSession session = request.getSession(false);if (session != null && session.getAttribute("userinfo") != null) {//说明已经登陆,可以放行return true;}// 执行到这行表示未登录,未登录就重定向到到登陆页面response.sendRedirect("/user/login");return false;}
}
WebMvcConfigurer
的 addInterceptors
方法中。import org.springframework.beans.factory.annotation.Autowired;
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 AppConfig implements WebMvcConfigurer {@Autowiredprivate LoginIntercept loginIntercept;@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(loginIntercept).addPathPatterns("/**").excludePathPatterns("/user/login").excludePathPatterns("/user/reg").excludePathPatterns("/login.html").excludePathPatterns("/reg.html").excludePathPatterns("/**/*.css").excludePathPatterns("/**/*.jpg");}
}
其中函数的作用:
addPathPatterns
:表示需要拦截的 URL,**
的意思表示所有方法,在这表示拦截所有的方法excludePathPatterns
:表示排除的 URL,也就是需要放行的方法。通常我们应该将登陆和注册功能放行以及各种静态资源(图片、JS 和 CSS 文件)。经过拦截器的加入后,我们程序的执行流程将会是下图这样:
从源码来看,所有的Controller
执行时,都会通过一个调度器DispatcherServlet
来进行实现,我们可以从SpringBoot
的打印日志看出这一点:
所有方法都会被其中的doDispatch
进行调度,进入源码观察,在我注释的地方,它先执行applyPreHandle
预处理方法,才会进入Controller
层。
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {HttpServletRequest processedRequest = request;HandlerExecutionChain mappedHandler = null;boolean multipartRequestParsed = false;WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);try {try {ModelAndView mv = null;Exception dispatchException = null;try {processedRequest = this.checkMultipart(request);multipartRequestParsed = processedRequest != request;mappedHandler = this.getHandler(processedRequest);if (mappedHandler == null) {this.noHandlerFound(processedRequest, response);return;}HandlerAdapter ha = this.getHandlerAdapter(mappedHandler.getHandler());String method = request.getMethod();boolean isGet = HttpMethod.GET.matches(method);if (isGet || HttpMethod.HEAD.matches(method)) {long lastModified = ha.getLastModified(request, mappedHandler.getHandler());if ((new ServletWebRequest(request, response)).checkNotModified(lastModified) && isGet) {return;}}// 进行预处理,也就是进入拦截器if (!mappedHandler.applyPreHandle(processedRequest, response)) {return;}//执行Controller层的业务方法mv = ha.handle(processedRequest, response, mappedHandler.getHandler());if (asyncManager.isConcurrentHandlingStarted()) {return;}this.applyDefaultViewName(processedRequest, mv);mappedHandler.applyPostHandle(processedRequest, response, mv);} catch (Exception var20) {dispatchException = var20;} catch (Throwable var21) {dispatchException = new NestedServletException("Handler dispatch failed", var21);}this.processDispatchResult(processedRequest, response, mappedHandler, mv, (Exception)dispatchException);} catch (Exception var22) {this.triggerAfterCompletion(processedRequest, response, mappedHandler, var22);} catch (Throwable var23) {this.triggerAfterCompletion(processedRequest, response, mappedHandler, new NestedServletException("Handler processing failed", var23));}} finally {if (asyncManager.isConcurrentHandlingStarted()) {if (mappedHandler != null) {mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);}} else if (multipartRequestParsed) {this.cleanupMultipart(processedRequest);}}}
再次进入applyPreHandle
这个方法的源码去进行查看:
boolean applyPreHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {for(int i = 0; i < this.interceptorList.size(); this.interceptorIndex = i++) {HandlerInterceptor interceptor = (HandlerInterceptor)this.interceptorList.get(i);if (!interceptor.preHandle(request, response, this.handler)) {this.triggerAfterCompletion(request, response, (Exception)null);return false;}}return true;}
这里就特别清晰了,它获取到了我们前面定义的所有HandlerInterceptor
对象,并且执行了我们重写了preHandle
方法,这里面就写了我们用户登陆权限验证的方法逻辑,这就是拦截器的实现原理。
可以看出,Spring
的拦截器也是通过动态和环绕通知的思想实现的。
通过拦截器我们可以在所有请求地址前添加一个任意前缀,比如我们添加一个叫api
的前缀,可以在实现WebMvcConfigurer
接口的类中重写方法configurePathMatch
,c->true
表示启动该前缀。
@Overridepublic void configurePathMatch(PathMatchConfigurer configurer) {configurer.addPathPrefix("api", c -> true);}