zoukankan      html  css  js  c++  java
  • SpringBoot中使用Interceptor

    1.创建自定义的拦截器并实现HandlerInterceptor接口

    package com.demo.common.interceptor;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.web.servlet.HandlerInterceptor;
    import org.springframework.web.servlet.ModelAndView;
    
    public class MyInterceptor implements HandlerInterceptor{
        
        Logger logger = LoggerFactory.getLogger(MyInterceptor.class);
        
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
                throws Exception {
            logger.info("preHandle :" +request.getContextPath());
            HttpSession session = request.getSession();
            if (session.getAttribute("user") != null)
                return true;
    
            // 跳转登录
            String url = request.getContextPath() + "/login";
            response.sendRedirect(url);
            return true;
        }
    
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                ModelAndView modelAndView) throws Exception {
            
        }
    
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
                throws Exception {
            
        }
    
    }
    2.创建一个java类继承WebMvcConfiguraeAdapter并重写addInterceptor方法(该类用来添加配置拦截器在该类中添加配置拦截器,以及配置过滤)
    package com.demo.common.interceptor;
    
    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 AddInterceptor extends WebMvcConfigurerAdapter{
        
        public void addInterceptors(InterceptorRegistry registry){
            registry.addInterceptor(new MyInterceptor())
            .addPathPatterns("/**")
            .excludePathPatterns("/login")
            .excludePathPatterns("/loginPost");
        }
    }
  • 相关阅读:
    第13讲- Android之消息提示Notification
    第12讲- Android之消息提示Toast
    第11讲- Android中进程及其优先级
    第10讲- UI线程阻塞及其优化
    第09讲 常见事件响应2
    听李玫瑾未成年人(0-18岁)心理讲座笔记
    管理经典:善待20%的骨干人才
    再学《多管事,不如抓重点》
    解决难题的最好方法是什么
    孩子14岁前,请一定要告诉他们这7句话!
  • 原文地址:https://www.cnblogs.com/chao555/p/9573102.html
Copyright © 2011-2022 走看看