栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 软件开发 > 后端开发 > Java

springboot+interceptor

Java 更新时间:发布时间: 百科书网 趣学号
1.在启动类同级或者下级目录中创建一个拦截器的配置类
@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("/**");
    }}
转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/1065169.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号