1、定义过滤器
package cn.study.filter;
import java.io.IOException;
import java.util.Optional;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpReq = (HttpServletRequest) request;
HttpServletResponse httpResp = (HttpServletResponse) response;
// 判断条件
boolean condition = ... ;
if (!condition) {
httpResp.sendError(401);
} else {
chain.doFilter(request, response);
}
}
}
2、添加过滤器
package cn.study.config;
import cn.study.filter.MyFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.HashSet;
import java.util.Set;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Bean
public FilterRegistrationBean<MyFilter> registration() {
Set<String> pathSet = new HashSet<>();
FilterRegistrationBean<MyFilter> filterRegistrationBean = new FilterRegistrationBean<>();
filterRegistrationBean.setFilter(new MyFilter());
pathSet.forEach(path -> filterRegistrationBean.addUrlPatterns(path));
filterRegistrationBean.setName("MyFilter");
filterRegistrationBean.setOrder(1);
return filterRegistrationBean;
}
}
3、只用将上述代码中的pathSet替换成需要过滤的路径集合,功能就实现了,下面介绍两种获取方式,可以直接在WebMvcConfig中添加
package cn.study.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Autowired
WebApplicationContext applicationContext;
/**
*
*/
public Set<String> getControllerPathSet1() {
Set<String> pathSet = new HashSet<String>();
RequestMappingHandlerMapping handlerMapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
handlerMapping.getHandlerMethods().values().forEach(handlerMethod -> {
Class<?> clazz = handlerMethod.getMethod().getDeclaringClass();
if (clazz.getName().startsWith("cn.study")) {
RequestMapping annotation = clazz.getAnnotation(RequestMapping.class);
if (annotation != null) {
Arrays.asList(annotation.value()).forEach(value -> pathSet.add(value + "/*"));
}
}
});
return pathSet;
}
/**
*
*/
public Set<String> getControllerPathSet2() {
String packageName = "cn.study";
Set<String> pathSet = new HashSet<>();
String packageDirName = packageName.replace('.', '/');
try {
URL url = Thread.currentThread().getContextClassLoader().getResource(packageDirName);
String protocol = url.getProtocol();
if ("file".equals(protocol)) {
String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
getControllerPath(packageName, filePath, pathSet);
}
} catch (IOException e) {
e.printStackTrace();
}
return pathSet;
}
private void getControllerPath(String packageName, String packagePath, Set<String> pathSet) {
File dir = new File(packagePath);
if (!dir.exists() || !dir.isDirectory()) {
return;
}
File[] dirfiles = dir.listFiles(file -> (file.isDirectory()) || (file.getName().endsWith("Controller.class")));
for (File file : dirfiles) {
if (file.isDirectory()) {
getControllerPath(packageName + "." + file.getName(), file.getAbsolutePath(), pathSet);
} else {
String className = file.getName().substring(0, file.getName().length() - 6);
try {
Class<?> clazz = Class.forName(packageName + '.' + className);
RequestMapping annotation = clazz.getAnnotation(RequestMapping.class);
if (annotation != null) {
Arrays.asList(annotation.value()).forEach(value -> pathSet.add(value + "/*"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
}
4、第一种方法使用Spring自带的方法更通用一些,第二种要求所有controller必须以Controller作为结尾
参考文章1:https://www.cnblogs.com/Leechg/p/10058763.html
参考文章2:https://blog.csdn.net/tt____tt/article/details/82012999