1.创建一个类,继承与HandlerInterceptor,并实现3个方法。在preHandle方法中,调用controller组件前被调用,可以在此做业务逻辑。下面是每次调用前,都进行登录的判断。
public class LoginInterceptor implements HandlerInterceptor {
private Logger LOGGER = LoggerFactory.getLogger(LoginInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
LOGGER.info("preHandle");
Object object = request.getSession().getAttribute("name");
if(null!=object&&object instanceof String){
String user = (String)object;
if((user.equals("fangdingjie"))){
LOGGER.info("登录成功");
return true;
}
}
LOGGER.info("请登录");
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
LOGGER.info("postHandle");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
LOGGER.info("afterCompletion");
}
}
2.在App启动类中创建一个子类,继承于WebMvcConfigurationSupport,并使用@Configuration注解.
addPathPatterns对指定的路径进行拦截,"/**"表示所有路径都进行拦截
excludePathPatterns表示不拦截的路径
@Configuration
static class WebMvcConfigurer extends WebMvcConfigurationSupport {
//增加拦截器
public void addInterceptors(InterceptorRegistry registry){
registry.addInterceptor(new LoginInterceptor()) //指定拦截器类
.addPathPatterns("/**") //指定该类拦截的url
.excludePathPatterns("/login");; //不拦截
}
}
网友评论