文章目录
1 按照Spring MVC的方式编写一个拦截器类,实现HandlerInterceptor接口
package com.bjpowernode.springboot.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginInterceptor implements HandlerInterceptor {
@Override //进入Controller之前执行该方法
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//登录拦截的业务逻辑
System.out.println("-------登录请求拦截器--------------");
System.out.println(request.getRequestURI().toString());
Object object = request.getSession().getAttribute("user");
if (object == null) {
System.out.println("用户没有登录");
return false;
}
//继续提交请求,false 请求不提交了
return true;
}
}
2 通过配置类注册拦截器
在03-springboot-web中创建一个config包,创建一个配置类InterceptorConfig,并实现WebMvcConfigurer接口, 覆盖接口中的addInterceptors方法,并为该配置类添加@Configuration注解,标注此类为一个配置类,让Spring Boot 扫描到,这里的操作就相当于SpringMVC的注册拦截器 ,@Configuration就相当于一个applicationContext-mvc.xml
package com.bjpowernode.springboot.config;
import com.bjpowernode.springboot.interceptor.LoginInterceptor;
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 InterceptorConfig implements WebMvcConfigurer {