SpringBoot 2.x 拦截器注册方式
在SpringBoot 1.x中我们可以通过继承WebMvcConfigurerAdapter
这个类来实现注册拦截器的功能,但在SpringBoot 2.x中,却不推荐我们通过这种方式来实现,我们可以通过继承WebMvcConfigurationSupport
这个类来实现。
我们可以通过继承HandlerInterceptorAdapter
这个抽象类来实现拦截器的功能。
拦截器
import com.syumi.aliossservice.content.Constant;
import com.syumi.aliossservice.pojo.UserInfo;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class PermissionInteceptor extends HandlerInterceptorAdapter {
private static String whiteList;
public void setWhiteList(String whiteList) {
PermissionInteceptor.whiteList = whiteList;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String path = request.getServletPath();
if(whiteList.contains(path)) {
return true;
}
UserInfo userInfo = (UserInfo) request.getSession().getAttribute(Constant.USERINFO);
if (userInfo != null) {
return true;
}
return false;
}
}
此外,我们还可以通过实现接口HandlerInterceptor
来实现拦截器功能
import com.syumi.aliossservice.content.Constant;
import com.syumi.aliossservice.pojo.UserInfo;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class PermissionInteceptor implementsHandlerInterceptor{
private static String whiteList;
public void setWhiteList(String whiteList) {
PermissionInteceptor.whiteList = whiteList;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String path = request.getServletPath();
if(whiteList.contains(path)) {
return true;
}
UserInfo userInfo = (UserInfo) request.getSession().getAttribute(Constant.USERINFO);
if (userInfo != null) {
return true;
}
return false;
}
}
注册拦截器
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import java.util.List;
@Configuration
public class AliOssServiceWebMVCConfigurationAdatper extends WebMvcConfigurationSupport {
@Value("#{'${whitelist}'.split(',')}")
private List<String> whiteList;
PermissionInteceptor permissionInteceptor = new PermissionInteceptor();
@Override
protected void addInterceptors(InterceptorRegistry registry) {
permissionInteceptor.setWhiteList(whiteList);
registry.addInterceptor(permissionInteceptor).addPathPatterns("*");
super.addInterceptors(registry);
}
}