这个代码写了很久了,多久呢?2018年12-20号写的。。。。
废话不多说,简化一下,作为笔记。
注:
public class springmvcConfig extends WebMvcConfigurerAdapter 这种写法已废弃,WebMvcConfigurerAdapter不再推荐使用。
1:新建一个拦截器类,实现 HandlerInterceptor 接口
1 class InterceptorConfig implements HandlerInterceptor { 2 private static final Logger log = LoggerFactory.getLogger(Filter.class); 3 4 /** 5 * httpServletRequest存储请求信息,如ip地址,url等 6 * preHandle进入Handler方法之前执行了,使用于身份认证,身份授权,登陆校验等,比如身份认证,用户没有登陆, 7 * 拦截不再向下执行,返回值为 false ,即可实现拦截;否则,返回true时,拦截不进行执行 8 **/ 9 @Override 10 public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { 11 String ip = httpServletRequest.getRemoteAddr(); 12 String url = httpServletRequest.getRequestURI(); 13 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); 14 Date date = new Date(); 15 String time = sdf.format(date); 16 log.info("时间:{},IP地址:{},目标URL:{}", time, ip, url); 17 18 return true; 19 } 20 21 /** 22 * 进入Handler方法之后,返回ModelAndView之前执行,使用场景从ModelAndView参数出发, 23 * 比如,将公用的模型数据在这里传入到视图,也可以统一指定显示的视图等 24 **/ 25 @Override 26 public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { 27 log.info("i am in hendler before return modelandview..."); 28 29 } 30 31 /** 32 * 在执行Handler完成后执行此方法,使用于统一的异常处理,统一的日志处理等 33 **/ 34 @Override 35 public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { 36 log.info("i am out of from handler..."); 37 38 } 39 }
2:新建一个mvc配置类实现 WebMvcConfigurer 接口,并加上 @Configuration 声明其为配置类:
@Configuration public class SpringmvcConfig implements WebMvcConfigurer{ private static final Logger log = LoggerFactory.getLogger(SpringmvcConfig.class); //图片映射 @Value("${images.path}") private String imagesRoot; @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { log.info("图片静态资源路径:{}", imagesRoot);
registry.addResourceHandler("/images/**").addResourceLocations(imagesRoot); } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new InterceptorConfig()); } }
3:最后上截图,并标明拦截器的个方法执行顺序,如图:
1:执行Prehandler
2:执行Controller中的代码
3:在返回ModelAndView之前执行postHandler
4:最后执行afterCompletion
若有不对望指正免得无人子弟,觉得写得可以的同学点个赞哦~