原创

实现在SpringBoot项目启动时对所有URL进行扫描


想对项目URL进行扫描自然离不开对应的注解。

说起注解,自然而然的就会想到Annotation,也就是java.lang.annotation.Annotation,通过观察类关系树状图

在这里插入图片描述

我们不难发现Annotation下有个WebServlet接口,再通过输出语句我们可以看到里面包含了我们想要的url信息,如下图

在这里插入图片描述

接下来为了得到WebServlet接口里面的value值也就是url,我们可以将Annotation这个接口强制转化成WebServlet

WebServlet webServlet= (WebServlet) annotation;

然后通过

String[] urls=webServlet.value();

可获得urls数组遍历一下就可以得到我们想要的url

那么如何在项目启动时获取URL呢?

步骤如下

1、声明要扫描URL的包路径

String packageName = "com.servlet.";

2、用this.getClass().getResource("/").getPath()获取类工作路径也就是classes文件路径,然后用File类获取类加载的根路径

File f = new File(this.getClass().getResource("/").getPath());

3、用创建好的File类递归获取路径下的所有类名

public void findFile(File folder, String packageName){
        File[] files = folder.listFiles();
        for (File file:files) {
            if (file.isDirectory()) {
                findFile(file, packageName + file.getName() + ".");
            } else {
                getUrl(file.getName(), packageName);
            }
        }
    }

4、用上面获取到的文件名(file.getName())去除.class后缀获得类名,然后用Class.forName加载第一步的包名拼接上类名 获得类对象

Class clazz = Class.forName(packageName + name);

5、然后用clazz .getAnnotations()可以获得当前类的Annotation对象

Annotation[] annotations=clazz.getAnnotations();

6、强转为WebServlet接口(这里以WebServlet注解为例)

WebServlet webServlet= (WebServlet) a;

7、用webServlet.value()获取URL

总的代码如下(能扫描WebServlet、RequestMapping、GetMapping、PostMapping、PutMapping和DeleteMapping注解):

/**
 * 扫描所有URL装入permissions容器中
 * @Author: 陌攻
 * @Description:
 * @Date: Created in 21:31 2020/5/3
 * @Modified By:
 */
@Component
public class ScanningUrl {

    private final static Log log = LogFactory.getLog(ScanningUrl.class);

    private List<Permission> permissions=new ArrayList<Permission>();

    public ScanningUrl() {
//        scanningUrl();
    }

    public void scanningUrl() {
//        //获取了ScanningUrl这个类所在的jar包的绝对路径
//        String jarWholePath = ScanningUrl.class.getProtectionDomain().getCodeSource().getLocation().getFile();
//        try {
//            jarWholePath = java.net.URLDecoder.decode(jarWholePath, "UTF-8");//防止中文乱码
//        } catch (UnsupportedEncodingException e) {
//            log.info(e.toString());
//        }
        String packageName = "com.mogong.ssm.controller.";
        //System.getProperty("user.dir")获取用户当前工作目录
        File f = new File(this.getClass().getResource("/").getPath());// 获取类加载的根路径
        File file = new File(f+ SystemUtil.se+"com"+SystemUtil.se+"mogong"+SystemUtil.se+"ssm"+SystemUtil.se+"controller");
        file.setWritable(true, false);
        findFile(file, packageName);
    }
    public void findFile(File folder, String packageName){
        File[] files = folder.listFiles();
        for (File file:files) {
            if (file.isDirectory()) {
                findFile(file, packageName + file.getName() + ".");
            } else {
                getUrl(file.getName(), packageName);
            }
        }
    }
    public void getUrl(String filename, String packageName) {
        try {
            String name = filename.substring(0, filename.length() - 6);
            Class clazz = Class.forName(packageName + name);
            Annotation[] clazzAnnotations=clazz.getAnnotations();
            String urlPath="";//存放API主路径
            for (Annotation a:clazzAnnotations) {
                try{
                    RequestMapping requestMapping= (RequestMapping) a;
                    for (String url:requestMapping.value()) {
                        urlPath=url;
                    }
//                    try{
//                        WebServlet webServlet= (WebServlet) a;
//                        addApi("",webServlet.value(),"WebServlet");
//                    }catch (Exception e){}
                }catch (Exception e){}
            }
            Method[] methods = clazz.getDeclaredMethods();
            for (Method m:methods) {
                Annotation[] annotations=m.getAnnotations();
                for (Annotation a:annotations) {
                    try{
                        RequestMapping requestMapping= (RequestMapping) a;
                        addApi(urlPath,requestMapping.value(),"RequestMapping");
                    }catch (Exception e){}
                    try{
                        GetMapping getMapping= (GetMapping) a;
                        addApi(urlPath,getMapping.value(),"GetMapping");
                    }catch (Exception e){}
                    try{
                        PostMapping postMapping= (PostMapping) a;
                        addApi(urlPath,postMapping.value(),"PostMapping");
                    }catch (Exception e){}
                    try{
                        PutMapping putMapping= (PutMapping) a;
                        addApi(urlPath,putMapping.value(),"PutMapping");
                    }catch (Exception e){}
                    try{
                        DeleteMapping deleteMapping= (DeleteMapping) a;
                        addApi(urlPath,deleteMapping.value(),"DeleteMapping");
                    }catch (Exception e){}
                }
            }
        } catch (Exception e) {
            log.info("Exception = " + e.getLocalizedMessage());
        }
    }
    public void addApi(String urlPath,String[] myurls,String type){
        for (String url:myurls) {
            Permission permission=new Permission();
            permission.setUrl(urlPath+url);//urlPath+url:主路径拼接请求路径
            permission.setPermissionName(urlPath+url);
            permission.setType(type);
            permissions.add(permission);
        }
    }

    public List<Permission> getPermissions() {
        return permissions;
    }

    public void setPermissions(List<Permission> permissions) {
        this.permissions = permissions;
    }
}

最后在web.xml配置项目启动时初始化存储类调用该类的getPermissions()就可以了。

java
SpringBoot
  • 作者:陌攻(联系作者)
  • 发表时间:2020-05-30 19:13
  • 版权声明:自由转载-非商用-非衍生-保持署名(创意共享3.0许可证)
  • 公众号转载:请在文末添加作者公众号二维码
  • 评论