1.创建一个拦截器,实现HandlerInterceptor接口
package com.example.springboot.common.interceptor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class DuckTestInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
System.out.println(this.getClass().getName() + "<------>preHandle");
return true;
}
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
System.out.println(this.getClass().getName() + "<------>postHandle");
}
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
System.out.println(this.getClass().getName() + "<------>afterCompletion");
}
}
2.2:创建java类,继承WebMvcConfigurerAdapter,重写addInterceptors方法,把拦截器类添加到拦截器链中。
package com.example.springboot.common.config;
import com.example.springboot.common.interceptor.DuckTestInterceptor;
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.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class InterceptorRegister extends WebMvcConfigurerAdapter{
@Autowired
private DuckTestInterceptor duckTestInterceptor;
/**
* @Description 重写该方法可以通过服务器访问电脑本地文件
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry){
// file/** 服务器访问路径地址
registry.addResourceHandler( "file/**")
.addResourceLocations("file:" +"D:/project/"); // D:/project/ 本地文件存储地址
}
/*
* 添加spring中的拦截器
*/
@Override
public void addInterceptors(InterceptorRegistry registry){
registry.addInterceptor(duckTestInterceptor).addPathPatterns("/**");
}
}
3.测试
A@QG{(%ZXMMQ5@J@B_(WU{P.png