首先说明的一点是,2.0版本使用以前的继承已经过时,现在提供了新的接口WebMvcConfigurer和HandlerInterceptor。
一、需要自定义类,分别实现HandlerInterceptor和WebMvcConfigurer
实现HandlerInterceptor
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.huae.bean.Manager;
public class SysInterceptor implements HandlerInterceptor{
/**
* 进入拦截器后首先进入的方法
* 返回false则不再继续执行
* 返回true则继续执行
*/
public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler)throws Exception{
//进行登陆验证
HttpSession session=request.getSession();
Manager userInfo = (Manager)session.getAttribute("userinfo");
if(userInfo==null){
response.sendRedirect(request.getContextPath()+"/login.html");
return false;
}
return true;
}
}
实现WebMvcConfigurer
@Configuration
public class SessionConfiguration implements WebMvcConfigurer{
@Override
public void addInterceptors(InterceptorRegistry registry) {
//创建自定义的拦截器类添加到配置中
SysInterceptor sitp=new SysInterceptor();
InterceptorRegistration ir =registry.addInterceptor(sitp);
//设置拦截器需要拦截的请求
ir.addPathPatterns("/**");
//设置拦截器不需要拦截的请求
ir.excludePathPatterns("/login.html","/static/**","/login");
}
}
这里需要注意的一点是 ir.excludePathPatterns("/login.html","/static/**","/login");
因为我的静态资源全都在static文件夹下,其中/static/**是放行静态资源,其余写法不推荐。
二、启动项目后,首先加载实现WebMvcConfigurer的类,然后进入拦截器中进行拦截验证