LoginHandlerInterceptor
package k.component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Object user = request.getSession().getAttribute("loginUser");
if (user == null) {
//未登陆,返回登陆页面
request.setAttribute("msg", "没有权限请先登陆");
request.getRequestDispatcher("/index.html").forward(request, response);
return false;
} else {
//已登陆,放行请求
return true;
}
}
}
MyMvcConfig
package k.config;
import k.component.LoginHandlerInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("login");
registry.addViewController("/index.html").setViewName("login");
registry.addViewController("/main.html").setViewName("dashboard");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//其他静态资源,与本文关系不大
// registry.addResourceHandler("/upload/**").addResourceLocations("file:"+ TaleUtils.getUplodFilePath()+"upload/");
//需要配置1:----------- 需要告知系统,这是要被当成静态文件的!
//第一个方法设置访问路径前缀,第二个方法设置资源路径
// registry.addResourceHandler("/asserts/**").addResourceLocations("classpath:/static/asserts");
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
//super.addInterceptors(registry);
//静态资源; *.css , *.js
// SpringBoot2.x静态资源映射 /asserts/**
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/index.html", "/", "/user/login", "/asserts/**");
}
}