獲取springmvc中全部的Controller

@RequestMapping(value = "getUrlMapping") public ModelAndView  getUrlMapping(HttpServletRequest request) {
    WebApplicationContext wc = getWebApplicationContext(request.getSession().getServletContext());
    RequestMappingHandlerMapping rmhp = (RequestMappingHandlerMapping)wc.getBean("org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0");
    Map<RequestMappingInfo, HandlerMethod> map = rmhp.getHandlerMethods(); for (Iterator<RequestMappingInfo> iterator = map.keySet().iterator(); iterator
            .hasNext();) {
        RequestMappingInfo info = iterator.next();
        System.out.print(info.getConsumesCondition());
        System.out.print(info.getCustomCondition());
        System.out.print(info.getHeadersCondition());
        System.out.print(info.getMethodsCondition());
        System.out.print(info.getParamsCondition());
        System.out.print(info.getPatternsCondition());
        System.out.print(info.getProducesCondition());

        System.out.print("===");

        HandlerMethod method = map.get(info);
        System.out.print(method.getMethod().getName() + "--");
        System.out.print(method.getMethodAnnotation(RequestMapping.class).params()[0]);
        System.out.println();
    } return null;
} public WebApplicationContext getWebApplicationContext(ServletContext sc) { return WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
}



代碼如上: java

須要注意的是 web


RequestMappingHandlerMapping rmhp = (RequestMappingHandlerMapping)wc.getBean("org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0");

取RequestMappingHandlerMapping 的時候,若是集成了多個展現方式的話,RequestMappingHandlerMapping 對象會有多個,直接經過class是娶不到的。可是能夠經過上面的方式獲取到。 spring




package com.wy.controller.system;

import com.wy.util.JsonHelper;
import com.wy.vo.BaseForm;
import com.wy.vo.system.RequestToMethodItem;
import javassist.*;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.LocalVariableAttribute;
import javassist.bytecode.MethodInfo;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
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;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.util.*;


/**
 * 用戶Controller
 */
@Controller
@RequestMapping("/sandbox")
public class SandboxController {

    private static final Logger LOGGER = Logger.getLogger(SandboxController.class);


    @RequestMapping("/index")
    public ModelAndView index(Long id, HttpServletRequest request, HttpServletResponse response) throws IOException, ClassNotFoundException, NotFoundException {
        ApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext());
        RequestMappingHandlerMapping handlerMapping = (RequestMappingHandlerMapping) ac.getBean("org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#1");
        List<RequestToMethodItem> requestToMethodItemList = loadRequestToMethodItem(handlerMapping);
        Map<String, Object> results = new HashMap<String, Object>();
        results.put("data", requestToMethodItemList);

        //生成json

        for (RequestToMethodItem item:requestToMethodItemList){
            String url=item.getRequestUrl();
            String[] urls=url.split("//");

        }
        return new ModelAndView("/sandbox/index", results);

    }

    private List<RequestToMethodItem> loadRequestToMethodItem(RequestMappingHandlerMapping handlerMapping) {
        List<RequestToMethodItem> requestToMethodItemList = new ArrayList<RequestToMethodItem>();
        Map<RequestMappingInfo, HandlerMethod> map = handlerMapping.getHandlerMethods();
        for (Map.Entry<RequestMappingInfo, HandlerMethod> m : map.entrySet()) {
            RequestMappingInfo requestMappingInfo = m.getKey();
            HandlerMethod mappingInfoValue = m.getValue();
            RequestMethodsRequestCondition methodCondition = requestMappingInfo.getMethodsCondition();
            int methodsSize = requestMappingInfo.getMethodsCondition().getMethods().size();
            String requestType = methodsSize == 0 ? "GET" : methodCondition.getMethods().toString();
            String requestUrl = requestMappingInfo.getPatternsCondition().toString();
            String controllerName = mappingInfoValue.getBeanType().toString();
            String requestMethodName = mappingInfoValue.getMethod().getName();
            Class<?>[] methodParamTypes = mappingInfoValue.getMethod().getParameterTypes();

            Map methodParam = loadMethodParam(requestMappingInfo, mappingInfoValue);
            RequestToMethodItem item = new RequestToMethodItem(requestUrl, requestType, controllerName, requestMethodName, methodParamTypes, methodParam);
            requestToMethodItemList.add(item);

        }
        return requestToMethodItemList;
    }

    private Map loadMethodParam(RequestMappingInfo requestMappingInfo, HandlerMethod mappingInfoValue) {
        try {

            String controllerName = mappingInfoValue.getBeanType().getName();
            String requestMethodName = mappingInfoValue.getMethod().getName();
            return getMethodParamNames2(controllerName, requestMethodName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    public Map getMethodParamNames2(String clazzName, String method) throws NotFoundException, ClassNotFoundException {

        Map map = new HashMap();
        ClassPool pool = ClassPool.getDefault();
        pool.insertClassPath(new ClassClassPath(this.getClass()));

        CtClass cc = pool.get(clazzName);
        CtMethod cm = cc.getDeclaredMethod(method);
        CtClass[] parameterTypes = cm.getParameterTypes();

        MethodInfo methodInfo = cm.getMethodInfo();
        CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
        LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
        if (attr == null)
            throw new RuntimeException(cc.getName());

        String[] paramNames = new String[cm.getParameterTypes().length];
        int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;
        for (int i = 0; i < paramNames.length; i++) {
            paramNames[i] = attr.variableName(i + pos);
            String name = attr.variableName(i + pos);
            Class c = Class.forName(parameterTypes[i].getName());
            Class superClass = c.getSuperclass();

            if (null != superClass) {
                if (BaseForm.class.getName().equals(c.getSuperclass().getName())) {
                    Map<String, String> map2 = getClassFields(c, true);
                    map.putAll(map2);
                    continue;
                }
            }
            if (HttpServletRequest.class.getName().equals(c.getName())) {
                continue;
            }
            if (HttpServletResponse.class.getName().equals(c.getName())) {
                continue;
            }
            if (BindingResult.class.getName().equals(c.getName())) {
                continue;
            }
            if (BaseForm.class.getName().equals(c.getName())) {
                Map<String, String> map2 = getClassFields(BaseForm.class, false);
                map.putAll(map2);
                continue;
            }
            map.put(name, parameterTypes[i].getSimpleName());
        }
        return map;
    }

    /**
     * 獲取類實例的屬性值
     *
     * @param clazz              類名
     * @param includeParentClass 是否包括父類的屬性值
     * @return 類名.屬性名=屬性類型
     */
    public static Map<String, String> getClassFields(Class clazz, boolean includeParentClass) {
        Map<String, String> map = new HashMap<String, String>();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            map.put(field.getName(), field.getType().getSimpleName());
        }
        if (includeParentClass)
            getParentClassFields(map, clazz.getSuperclass());
        return map;
    }

    /**
     * 獲取類實例的父類的屬性值
     *
     * @param map   類實例的屬性值Map
     * @param clazz 類名
     * @return 類名.屬性名=屬性類型
     */
    private static Map<String, String> getParentClassFields(Map<String, String> map, Class clazz) {
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            map.put(field.getName(), field.getType().getSimpleName());
        }
        if (clazz.getSuperclass() == null) {
            return map;
        }
        //getParentClassFields ( map, clazz.getSuperclass ( ) );
        return map;
    }


}
相關文章
相關標籤/搜索