如何在SpringMVC中获取项目里的所有Action

需求

在开发过程中有时候会遇到这样的需求:获取系统中所存在的所有Action(url)。这里所说的项目指依赖SpringMVC框架的项目。

代码

@Controller
public class DemoController {

    private final RequestMappingHandlerMapping handlerMapping;

    @Autowired
    public DemoController(RequestMappingHandlerMapping handlerMapping) {
        this.handlerMapping = handlerMapping;
    }
    
    @RequestMapping(value = "/all_requests",method = RequestMethod.GET)
    public @ResponseBody List<Map<String, String>> getRequests(){
        List<Map<String, String>> requests = new ArrayList<Map<String,String>>();
        Map<RequestMappingInfo, HandlerMethod> tmp = this.handlerMapping.getHandlerMethods();
        Iterator<Entry<RequestMappingInfo, HandlerMethod>> it = tmp.entrySet().iterator();
        while (it.hasNext()) {
            Entry<RequestMappingInfo, HandlerMethod> entry = it.next();
            RequestMappingInfo key = entry.getKey();
            HandlerMethod handlerMethod = entry.getValue();
            Map<String,  String> req = new HashMap<String, String>();
            req.put("name", handlerMethod.getBeanType().getSimpleName() +"_"+ handlerMethod.getMethod().getName());
            req.put("url", key.getPatternsCondition().toString().replaceAll("\\[|\\]", ""));
            requests.add(req);
        }
        
        return requests;
    }
}


你可能感兴趣的:(springMVC,获取,actions,所有)