- 这里我的需求是只有用户登录后才允许用户访问除登录页面的所有页面
-
先创建一个类实现Inteceptor接口,重写里边的(预先)拦截的那个方法pre啥啥那个,在方法内取出Session中存放的登录用户信息,如果没有就是未登录,那么久返回false,当返回true的时候,拦截器放行。
/* 登录拦截器 */ @Component public class LoginInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { Admin admin = (Admin) request.getSession().getAttribute(Const.ADMIN); Teacher teacher = (Teacher) request.getSession().getAttribute(Const.TEACHER); Student student = (Student) request.getSession().getAttribute(Const.STUDENT); if(!StringUtils.isEmpty(admin) || !StringUtils.isEmpty(teacher) ||!StringUtils.isEmpty(student)){ //已登录状态返回true return true; } response.sendRedirect(request.getContextPath()+"/system/login"); return false; }
-
然后我们虽然创建了拦截器,但是并没有使用上,此时我们需要写一个类去实现WebMvcConfigurer,强调一下,这里类上需要@Configuration注解。
@Configuration public class MyWebMvcConfigurer implements WebMvcConfigurer { /* 我只重写了这一个方法就实现了我想要的功能,如果后续有需求,会补充后两个的讲解 这个方法是添加拦截器,先给一个拦截器对象,然后那个固定,再那个是不需要拦截的页面。 */ @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**") .excludePathPatterns("/system/login"); } /*@Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/"); } @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("/login"); }*/ }