
@Component
@Slf4j
public class ViewMappingInterceptor implements HandlerInterceptor {}
2.实现接口的方法
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.debug("============preHandle============");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
log.debug("============postHandle============");
// 判断请求是否为接口,如果是接口则直接返回
if (modelAndView == null){
// 如果为空则不是请求页面
return;
}
// 判断页面请求是否为重定向或者转发,如果是则直接返回
if (modelAndView.getViewName().startsWith("redirect")||
modelAndView.getViewName().startsWith("forward")){return;}
// 获取请求路经
String path = request.getServletPath();
// 判断modelMap中是否有template,有则跳过,如果没有则设置template
String template = (String) modelAndView.getModelMap().get("template");
if (StringUtils.isBlank(template)){
modelAndView.getModelMap().addAttribute("template",
path.substring(1,path.length()));
}
// 将处理之后的结果返回
HandlerInterceptor.super.postHandle(request,response,handler,modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
log.debug("============afterHandle============");
}
解释:案例实现的是将请求路径的model域中添加页面路径功能,首先判断是否想要访问页面,然后判断是否是请求转发或者重定向,最后根据请求的路径将前端thymeleaf页面所引入的页面路径 template存入域中
3.将拦截器注册到webMvcConfig类中去
@Configuration
// 设置配置生效时期(在WebMvcAutoConfiguration配置生效后生效即与该配置重复则覆盖前一个配置内容覆盖)
@AutoConfigureAfter({WebMvcAutoConfiguration.class})
public class WebMvcConfig implements WebMvcConfigurer {
@Autowired
private ViewMappingInterceptor viewMappingInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(viewMappingInterceptor).addPathPatterns("/**");
}}