Java – how to determine the controller (spring) for a given URL

How to use spring defaultannotationhandlermapping to find the controller that will eventually process the given URL

I have this at present, but I think it should be clearer than iterating over 100 request mappings:

public static Object getControllerForAction(String actionURL) {
    ApplicationContext context = getApplicationContext();
    AnnotationHandlerMapping mapping = (AnnotationHandlerMapping) context.getBean("annotationMapper");
    PathMatcher pathMatcher = mapping.getPathMatcher();
    for (Object key: mapping.getHandlerMap().keySet()) {
        if (pathMatcher.match((String) key,actionURL)){
            return mapping.getHandlerMap().get(key);
        }
    }
    return null;
}

Solution

For the purpose of this problem, all interesting methods in defaultannotationhandlermapping and its superclass are protected, so the external code is invisible However, writing a custom subclass of defaultannotationhandlermapping will override these methods and make them public, which will be trivial

Since you need to be able to provide a path instead of a request object, I recommend using the lookuphandler of abstracturlhandlermapping as a good candidate It still needs you to provide a request object and path for it, but the request object is only used to pass to the validatehandler () method, which does nothing, so you may provide null there

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>