spring boot 获取项目全部URL

来源:互联网 发布:cat翻译软件 编辑:程序博客网 时间:2024/05/18 03:57

spring boot 项目在做URL权限控制的时候需要获得全部的URL,一个一个去controller中找费时费力。而且有的权限点的命名和URL有一定的对应关系。如果能用程序获得全部URL,将会省去很多事。下面就介绍一种获取URL的方法。在项目中添加如下Controller,请求/getAllUrl,即可看到项目所有的URL。当然也可以根据项目将URL写入数据库或写入配置文件。

import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.context.WebApplicationContext;import org.springframework.web.method.HandlerMethod;import org.springframework.web.servlet.mvc.method.RequestMappingInfo;import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.Set;@Controller@RequestMapping("/*")public class UrlController {    @Autowired    WebApplicationContext applicationContext;    @GetMapping("/getAllUrl")    @ResponseBody    public List<String> getAllUrl(){        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);        //获取url与类和方法的对应信息        Map<RequestMappingInfo,HandlerMethod> map = mapping.getHandlerMethods();        List<String> urlList = new ArrayList<>();        for (RequestMappingInfo info : map.keySet()){            //获取url的Set集合,一个方法可能对应多个url            Set<String> patterns = info.getPatternsCondition().getPatterns();            for (String url : patterns){                urlList.add(url);            }        }        return urlList;    }}