springBoot 登录拦截器

1、首选创建一个继承HandlerInterceptor的拦截器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
 
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
/**
  * 拦截器
  */
public class MyInterceptor implements HandlerInterceptor{
     //在请求处理之前进行调用(Controller方法调用之前
     @Override
     public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
         HttpSession session = httpServletRequest.getSession();
         String user = (String) session.getAttribute( "user" ); //获取登录的session信息
         if (user!=null){
             return true;
         }
         else {
httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+ "/login/index" );  //未登录自动跳转界面
             return false;
         }
     }
 
     //请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
     @Override
     public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
 
         System.out.println( "postHandle被调用\n" );
     }
 
     //在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)
     @Override
     public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
         System.out.println( "afterCompletion被调用\n" );
     }
}

  2、继承WebMvcConfigureAdapter类,覆盖其addInterceptors接口,注册自定义的拦截器:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
 
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
 
     /**
      * 注册拦截器
      */
     @Override
     public void addInterceptors(InterceptorRegistry registry) {
     //addPathPattern后跟拦截地址,excludePathPatterns后跟排除拦截地址
    registry.addInterceptor( new MyInterceptor()).addPathPatterns( "/**" ).excludePathPatterns( "/login/index" ).excludePathPatterns( "/login/login" );
     }
}

  

这样我们就可以在用户请求到达controller层实现登录拦截了,所有用户请求都会被拦截,在prehandle方法进行登录判断,返回true则验证通过,否则失败

大家有兴趣可以加我一起探讨技术,微信:3885115

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值