拦截器在springboot中只需要实现HandlerInterceptor接口,并重写preHandle方法
package com.hzy.config;
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 {
// 登录之后用户会有session
if (request.getSession().getAttribute("msg") == null) {
System.out.println("=============");
request.setAttribute("loginMsg","请先登录");
request.getRequestDispatcher("/index").forward(request,response);
return false;
} else {
return true;
}
}
}
当然了,我们还需要把该方法托管到SpringBoot中,写一个配置类,所谓配置类,在SpringBoot2.x后,可以直接@Configuration注解,实现WebMvcConfigurer接口,并重写addInterceptors方法
package com.hzy.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 拦截所有的资源,除了主页、登录请求、注册请求、注册完成和静态资源
registry.addInterceptor(new LoginHandlerInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/","/index","/login","/toRegister","/register","/css/**","/img/**","/js/**");
}
}