首页 > 编程语言 > 详细

springboot添加拦截器

时间:2019-09-26 10:19:50      阅读:134      评论:0      收藏:0      [点我收藏+]

链接:https://blog.csdn.net/zyp1376308302/article/details/81257510

(侵删)

实现拦截器的两个步骤

  1. 自定义拦截器实现HandlerInterceptor接口
  2. 创建一个配置类继承WebMvcConfigurerAdapter类并重写addInterceptors方法

 

代码

1、自定义拦截器

@Component
public class AdminLoginInterceptor implements HandlerInterceptor {
//    在请求处理之前调用,只有返回true才会执行请求
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
//        得到session
        HttpSession session = httpServletRequest.getSession(true);
//        得到对象
        Object admin = session.getAttribute("admin");
//        判断对象是否存在
        if(admin!=null){
            return true;
        }else{
//            不存在则跳转到登录页
            httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/login/adminLogin");
            return false;
        }
    }
//    试图渲染之后执行
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
// 在请求处理之后,视图渲染之前执行 @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { } }

2、自定义配置类继承WebMvcConfigurerAdapter

@SpringBootConfiguration
public class AdminLoginAdapter extends WebMvcConfigurerAdapter {
    @Autowired
    AdminLoginInterceptor adminLoginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(adminLoginInterceptor).addPathPatterns("/admin/**").excludePathPatterns("/login/**"); super.addInterceptors(registry); } }

.addPathPatterns("/admin/**")  :添加需要过滤的路径

.excludePathPatterns("/login/**") :去掉不需要过滤的路径

springboot添加拦截器

原文:https://www.cnblogs.com/cmz-32000/p/11588984.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!