标签:
有时候需要根据url反查controller,如果能获取所有的url,则不用跟据url去代码里搜了,方便开发人员、调试人员或交接人。
关键对象:RequestMappingHandlerMapping
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition; import org.springframework.web.servlet.mvc.condition.RequestMethodsRequestCondition; import org.springframework.web.servlet.mvc.method.RequestMappingInfo; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; @Controller public class MappingController { @Autowired private RequestMappingHandlerMapping requestMappingHandlerMapping; @RequestMapping(value = "/mappings") public String list(Model model) { List<HashMap<String, String>> urlList = new ArrayList<HashMap<String, String>>(); Map<RequestMappingInfo, HandlerMethod> map = requestMappingHandlerMapping.getHandlerMethods(); for (Map.Entry<RequestMappingInfo, HandlerMethod> m : map.entrySet()) { HashMap<String, String> hashMap = new HashMap<String, String>(); RequestMappingInfo info = m.getKey(); HandlerMethod method = m.getValue(); PatternsRequestCondition p = info.getPatternsCondition(); for (String url : p.getPatterns()) { hashMap.put("url", url); } hashMap.put("className", method.getMethod().getDeclaringClass().getName()); // 类名 hashMap.put("method", method.getMethod().getName()); // 方法名 RequestMethodsRequestCondition methodsCondition = info.getMethodsCondition(); String type = methodsCondition.toString(); if (type != null && type.startsWith("[") && type.endsWith("]")) { type = type.substring(1, type.length() - 1); hashMap.put("type", type); // 方法名 } urlList.add(hashMap); } model.addAttribute("list", urlList); return "/console/system/mappingList"; } }
然后再在页面上遍历list即可【java框架源码下载】
<table class="tableList" > <tr> <th>类名</th> <th>方法名</th> <th>URL</th> <th>类型</th> <tr> <c:forEach items="${list}" var="mvc" varStatus="status"> <tr id="${status.index}"> <td>${mvc.className}</td> <td>${mvc.method}</td> <td> <c:choose> <c:when test="${!fn:contains(mvc.url,‘}‘) and (mvc.type==‘GET‘ or mvc.type==‘‘)}"> <a href="${ctx}${mvc.url}" target="_blank">${mvc.url}</a> </c:when> <c:otherwise>${mvc.url}</c:otherwise> </c:choose> </td> <td>${mvc.type}</td> </tr> </c:forEach> </table>
spring mvc 获取所有的controller和url映射关系
标签:
原文地址:http://www.cnblogs.com/dayuebings/p/4788360.html