首页 > 代码库 > 扫描指定路径下的全部请求路径(基于SpringMVC)

扫描指定路径下的全部请求路径(基于SpringMVC)

通过上面两篇博客,我们能够得到指定类上的全部请求路径。现在需要的是,给定一个指定的路径,获取全部的请求路径。

public class RequestUrlScannerHelper {

    /**
     * 以下三个参数通过IOC注入进来
     */
    private String basePackage;                  //扫描的基础包
    private ResourcePatternResolver resolver;    //解析器
    
    private TypeFilter controlFilter = new AnnotationTypeFilter(Controller.class, false);
    private String pattern;
    private Set<Class<?>> matchControlerClass = new HashSet<Class<?>>();
    
    /**
     * 根据basePackage得到全部的class文件,并进行匹配,将满足条件的class存储与set集合中。
     * @throws IOException
     * @throws ClassNotFoundException
     */
    @PostConstruct
    public void init() throws IOException, ClassNotFoundException {
        pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(basePackage) + "/**/*.class";
        
        Resource[] resources = resolver.getResources(pattern);
        MetadataReaderFactory factory = new CachingMetadataReaderFactory(resolver);
        for(Resource resource : resources) {
            if(resource.isReadable()) {
                MetadataReader reader = factory.getMetadataReader(resource);
                
                if(controlFilter.match(reader, factory)) {
                    matchControlerClass.add(Class.forName(reader.getClassMetadata().getClassName()));
                }
            }
        }
    }
    
    public String getBasePackage() {
        return basePackage;
    }

    public void setBasePackage(String basePackage) {
        this.basePackage = basePackage;
    }

    public ResourcePatternResolver getResolver() {
        return resolver;
    }

    public void setResolver(ResourcePatternResolver resolver) {
        this.resolver = resolver;
    }
    
    /**
     * 
     * @return 指定包下的全部请求信息。
     * @throws NoSuchMethodException
     * @throws SecurityException
     * @throws IllegalAccessException
     * @throws IllegalArgumentException
     * @throws InvocationTargetException
     */
    public List<RequestUrlInfo> getAllRequestUrl() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        List<RequestUrlInfo> infos = new ArrayList<RequestUrlInfo>();
        
        for(Class<?> scannerClass : matchControlerClass) {
            infos.addAll(RequestUrlHelper.getInstance().getAllRequestUrlInfos(scannerClass));
        }
        
        return infos;
    }
}

 

扫描指定路径下的全部请求路径(基于SpringMVC)