分析步骤:
1.编写拦截器(实现HandlerInterceptor)
package com
.itheima
.interceptor
;
import lombok
.extern
.slf4j
.Slf4j
;
import org
.springframework
.web
.servlet
.HandlerInterceptor
;
import org
.springframework
.web
.servlet
.ModelAndView
;
import javax
.servlet
.http
.HttpServletRequest
;
import javax
.servlet
.http
.HttpServletResponse
;
@Slf4j
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request
, HttpServletResponse response
, Object handler
) throws Exception
{
log
.debug("这是MyInterceptor的preHandle方法。");
return true;
}
@Override
public void postHandle(HttpServletRequest request
, HttpServletResponse response
, Object handler
, ModelAndView modelAndView
) throws Exception
{
log
.debug("这是MyInterceptor的postHandle方法。");
}
@Override
public void afterCompletion(HttpServletRequest request
, HttpServletResponse response
, Object handler
, Exception ex
) throws Exception
{
log
.debug("这是MyInterceptor的afterCompletion方法。");
}
}
2.编写配置类实现WebMvcConfigurer,在该类中添加各种组件。
package com
.itheima
.config
;
import com
.itheima
.interceptor
.MyInterceptor
;
import org
.springframework
.context
.annotation
.Bean
;
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 MvcConfig implements WebMvcConfigurer {
@Bean
public MyInterceptor
myInterceptor(){
return new MyInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry
) {
registry
.addInterceptor(myInterceptor()).addPathPatterns("/*");
}
}
可以在Springboot项目中通过配置类添加各种组件