1.拦截器进行登录检查
/*登陆检查*/
//拦截器要注册到容器中
public class LoginHandlerInterceptor implements HandlerInterceptor {
//目标方法执行之前
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//获取session域,获取到loginUser,看是否登录
HttpSession session = request.getSession();
Object loginUser = session.getAttribute("loginUser");
if (loginUser==null){
//未登录,返回登录页面
//获取转发器,并转发
request.setAttribute("msg","没有权限请先登录");
request.getRequestDispatcher("/index.html").forward(request,response);
return false;
}else {
//已登录,放行
return true;
}
}
}
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//映射到login.html页面
registry.addViewController("/").setViewName("login");
registry.addViewController("/index.html").setViewName("login");
//做重定向
registry.addViewController("/main.html").setViewName("dashboard");
}
//将MyLocaleResolver加到注册
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
//注册拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
//拦截器拦截所有请求,但放行以下请求
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**").excludePathPatterns("/","/index.html","/login.html","/user/login","/webjars/**","/asserts/**");
}
}