注意点:注意点**
1.要在拦截器类里面依赖注入的话,要首先确保拦截器配置是由spring容器管理的,才能依赖注入
@Bean
public LogInterceptor getCommonInterceptor(){
return new LogInterceptor();
}
2.在配置拦截器的注册
registry.addInterceptor(getCommonInterceptor()).excludePathPatterns(“/log/**”);
若不加拦截路径,则默认配置拦截所有请求
切记配置拦截的uri做配置match时是不包含这个server.servlet.context-path项目父路径**
1.拦截器的配置
LogConfiguration.class
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.WebMvcConfigurerAdapter;
@Configuration
public class LogConfiguration extends WebMvcConfigurerAdapter{
@Bean
public LogInterceptor getCommonInterceptor(){
return new LogInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(getCommonInterceptor())
.excludePathPatterns("/log/**");
super.addInterceptors(registry);
}
}
2.拦截器内部实现
“`
import java.sql.Timestamp;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
//import hikvision.java2.service.remote.LogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
/**
* Created by zhangpan on 2018/9/11.
*/
@Component
public class LogInterceptor implements HandlerInterceptor {
private static Logger logger = LoggerFactory.getLogger(LogInterceptor.class);
//如果要在拦截器里依赖注入,确保此类先使用了@Bean
//@Autowired
// LogService logService;
//postHandler() - 在handler被执行后被调用
@Override
public void postHandle(HttpServletRequest request,HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception {
String requestUri = request.getRequestURI();
System.out.println("postHandle在实际的handler被执行后被调用");
}
//postHandler() - 在handler被执行后被调用
@Override
public void afterCompletion(HttpServletRequest request,HttpServletResponse response, Object handler, Exception ex)
throws Exception {
System.out.println("afterCompletion在实际的handler被执行后被调用");
}
}
注意点:
1.要在拦截器类里面依赖注入的话,要首先确保拦截器配置是由spring容器管理的,才能依赖注入
@Bean
public LogInterceptor getCommonInterceptor(){
return new LogInterceptor();
}
2.在配置拦截器的注册
registry.addInterceptor(getCommonInterceptor()).excludePathPatterns(“/log/**”);
若不加拦截路径,则默认配置拦截所有请求
切记配置拦截的uri做配置match时是不包含这个server.servlet.context-path项目父路径