RequestMappingHandlerMapping的用法

有时候,想查看应用请求对应的ur和方法l情况,可以用RequestMappingHandlerMapping这个类来处理,下面这个方法可以解决:

package cn.pclby.controller.util;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

/**
 * 查看项目所有URL对应的Controller和方法
 */
@Controller
public class Url2ControllerUtils {

    @Autowired
    private RequestMappingHandlerMapping requestMappingHandlerMapping;

    @RequestMapping(value = "/admin/util/url2controller")
    @ResponseBody
    public void list(HttpServletResponse response) {
        StringBuilder sb = new StringBuilder();
        sb.append("URL").append("--").append("Class").append("--").append("Function").append('\n');

        Map<RequestMappingInfo, HandlerMethod> map = requestMappingHandlerMapping.getHandlerMethods();
        for (Map.Entry<RequestMappingInfo, HandlerMethod> m : map.entrySet()) {
            RequestMappingInfo info = m.getKey();
            HandlerMethod method = m.getValue();
            sb.append(info.getPatternsCondition()).append("--");
            sb.append(method.getMethod().getDeclaringClass()).append("--");
            sb.append(method.getMethod().getName()).append('\n');
        }

        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            writer.print(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            writer.close();
        }

    }
}

需要注意下面几点:

(1)RequestMappingHandlerMapping这个类在程序中用@Autowired来自动装配得到对象,但实际上,spring容器是没有注入到这个bean的,这个可以用applicationContext.getBean("requestMappingHandlerMapping")方法来验证得到。

(2)RequestMappingHandlerMapping这个类的对象,只能在controller层用,并且要在申明了@RequestMapping的方法里面用,从RequestMappingHandlerMapping的源码注释里面可以看出:

/**
 * Creates {@link RequestMappingInfo} instances from type and method-level 
 * {@link RequestMapping @RequestMapping} annotations in 
 * {@link Controller @Controller} classes.
 *
 * @author Arjen Poutsma
 * @author Rossen Stoyanchev
 * @since 3.1
 */
public class RequestMappingHandlerMapping extends RequestMappingInfoHandlerMapping {
//省略
}

 

(3)其它一般用@Autowired来自动装配得到对象的bean,前提是要在spring容器里面注入,这个RequestMappingHandlerMapping不用注入,估计是spring里springMVC自己的机制引起的。

猜你喜欢

转载自breezylee.iteye.com/blog/2160876