SpringBoot自定义拦截器实现登录验证拦截

登录验证拦截是拦截器比较常用的场景之一。我们想做到对未登录的用户进行拦截,禁止其访问其他页面同时跳转到登录页面,那么就需要使用拦截器了。当然你也可以使用比较成熟的框架,比如Shiro就是比较优秀的,但是我们自己如何实现这个功能呢,下面通过配置自定义的拦截器实现,顺便学习一下拦截器。

1、登录Controller的实现

我们这里只简单的模拟场景。

@Controller
public class AuthController {
    @GetMapping("/login")
    public String login(){

        return "login";
    }

    @PostMapping("/login")
    public String login(String username, String password, HttpServletRequest request){
        HttpSession session = request.getSession();
        session.setAttribute("token", "authorized");  //对于登录的用户在session中添加登录标记

        return "login";
    }

}

2、配置拦截规则

由于我们用的SpringBoot版本较高,HandlerInterceptor已经实现了所有方法,所以我们这里只实现这个访问前的方法即可。

public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        System.out.println("preHandle");
        HttpSession session = request.getSession();
        if ("authorized"!=session.getAttribute("token")) {  //校验登录标记
            request.getRequestDispatcher("/login").forward(request, response);  //对于未登录的用户跳转到登录页面
            return false;
        }
        return true;
    }
}

3、配置WebMvcConfigurer拦截器

@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry){
        registry.addInterceptor(new AuthInterceptor())
            .addPathPatterns("/**")
            .excludePathPatterns("/login")  //过滤掉登录页面
            .excludePathPatterns("/static/**");  //过滤掉静态资源
    }
}

通过上面简单的配置一个自定义的登录验证的拦截器就实现了。

发布了141 篇原创文章 · 获赞 131 · 访问量 21万+

猜你喜欢

转载自blog.csdn.net/qq_41621362/article/details/105337661