動態爲Spring Boot項目中所有自定義的Controller添加過濾器的兩種方法

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章