1 增加自定义拦截器
首先定义一个拦截器
import org.springframework.web.servlet.HandlerInterceptor; @Component public class LoginInterceptor implements HandlerInterceptor { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //自定义逻辑 } }
2 自定义配置类
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer @Configuration public class AppWebAppConfigurer implements WebMvcConfigurer { @Autowired private LoginInterceptor loginInterceptor; /** * 自定义拦截器 */ @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(loginInterceptor); WebMvcConfigurer.super.addInterceptors(registry); } /** * 过滤静态资源不被拦截 */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**"); WebMvcConfigurer.super.addResourceHandlers(registry); } /** * 设置默认首页 */ @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("forward:/member/login.html"); WebMvcConfigurer.super.addViewControllers(registry); } }
注意要让Spring能扫描到你的类。
WebMvcConfigurer 这个类非常有用,需要好好研究。
文章评论