Spring MVC: get RequestMapping value in the method

2019-08-21 16:34发布

问题:

In my app, for certain reasons I would like to be able to get the value of the @RequestMapping in the corresponding methods, however, I can't find a way to do that. Here are more details about what I want:

Suppose, I have a method like this:

@RequestMapping(value = "/hello")
@ResponseBody
public void helloMethod(AtmosphereResource atmosphereResource) {
...
}

I would like to be able to get the mapping "/hello" within the method. I know, I can use placeholders in the mapping in order to get their values when the actual requests come, but I need a finite set of processable requests, and I don't want a chain of ifs or switches in my method.

Is it at all possible?

回答1:

This would effectively be the same, wouldn't it?

private final static String MAPPING = "/hello";

@RequestMapping(value = MAPPING)
@ResponseBody
public void helloMethod(AtmosphereResource atmosphereResource) {
   // MAPPING accessible as it's stored in instance variable
}

But to answer the original question: I wouldn't be surprised if there wasn't a direct way to access that, it's difficult to think of valid reasons to access this information in controller code (IMO one of biggest benefits of annotated controllers is that you can completely forget about the underlying web layer and implement them with plain, servlet-unaware methods)



回答2:

You can get get this method's annotation @RequestMapping as you would get any other annotation:

 @RequestMapping("foo")
 public void fooMethod() {
    System.out.printf("mapping=" + getMapping("fooMethod"));
 }

 private String getMapping(String methodName) {
    Method methods[] = this.getClass().getMethods();
    for (int i = 0; i < methods.length; i++) {
        if (methods[i].getName() == methodName) {
            String mapping[] = methods[i].getAnnotation(RequestMapping.class).value();
            if (mapping.length > 0) {
                return mapping[mapping.length - 1];
            }
        }
    }
    return null;
}

Here I pass method's name explicitly. See a discussion o how to obtain current method name, if absolutely necessary here: Getting the name of the current executing method



标签: spring-mvc