码迷,mamicode.com
首页 > 其他好文 > 详细

SprongBoot——拦截器

时间:2020-02-24 10:10:35      阅读:75      评论:0      收藏:0      [点我收藏+]

标签:OLE   操作   catch   object   post   rect   erro   配置   print   

拦截器的作用
拦截用户的请求并进行相应的处理,比如:判断用户是否登陆,是否在可购买时间内,记录日志信息等。

1.创建Interceptor类

public class TestInterceptor implements HandlerInterceptor{
 
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
         try{
            //统一拦截(查询当前session是否存在user)(这里user会在每次登陆成功后,写入session)
            User user=(User)request.getSession().getAttribute("USER");
            if(user!=null){
                return true;
            }
            response.sendRedirect(request.getContextPath()+"你的登陆页地址");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;  //如果设置为false时,被请求时,拦截器执行到此处将不会继续操作
                      //如果设置为true时,请求将会继续执行后面的操作
    }
     /**
     * 请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
         System.out.println("执行了TestInterceptor的postHandle方法");
    }
     /**
     * 在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        System.out.println("执行了TestInterceptor的afterCompletion方法");
    }
}

2.创建拦截器配置类

@Configuration
public class WebAppConfigurer implements WebMvcConfigurer {
 
 
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //註冊TestInterceptor拦截器
        InterceptorRegistration registration = registry.addInterceptor(new TestInterceptor());
        registration.addPathPatterns("/**");                    //所有路径都被拦截
        registration.excludePathPatterns("/","/error","/static/**");       //添加不拦截路径
 
    }
}

SprongBoot——拦截器

标签:OLE   操作   catch   object   post   rect   erro   配置   print   

原文地址:https://www.cnblogs.com/luckyhui28/p/12355307.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!