废话不多说,直接上代码,以下两种方式获取SpringMVC中注册的URL。
@Controller
public class UrlsController {
// 方法 1
@ResponseBody
@RequestMapping("/urls1")
public Object getUrlMapping(HttpServletRequest request) {
WebApplicationContext wc = RequestContextUtils.getWebApplicationContext(request);
RequestMappingHandlerMapping rmhp = wc.getBean(RequestMappingHandlerMapping.class);
Map<RequestMappingInfo, HandlerMethod> map = rmhp.getHandlerMethods();
List<String> urls = new ArrayList<>(map.size());
for (RequestMappingInfo info : map.keySet()) {
System.out.println(info.getPatternsCondition().toString() + "," + map.get(info).getBean().toString());
urls.add(info.getPatternsCondition().toString());
}
return urls;
}
// 方法 2
@Autowired
private RequestMappingHandlerMapping handlerMapping;
@ResponseBody
@RequestMapping("/urls2")
public Object index(Long id, HttpServletRequest request, HttpServletResponse response)
throws IOException, ClassNotFoundException {
Map<RequestMappingInfo, HandlerMethod> map = this.handlerMapping.getHandlerMethods();
List<String> urls = new ArrayList<>(map.size());
for(Map.Entry<RequestMappingInfo, HandlerMethod> entry : map.entrySet()) {
System.out.println(entry.getKey() + System.lineSeparator() + entry.getValue());
urls.add(entry.getKey().toString());
}
return urls;
}
}
对了注意不能Response返回RequestMappingInfo, HandlerMethod
对象,否则会报错。其他web.xml以及springmvc的配置都需要加上。
网友评论