Ibolit
Ibolit

Reputation: 9720

Spring MVC: get RequestMapping value in the method

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?

Upvotes: 0

Views: 4448

Answers (3)

Nikolas Freitas Mr Nik
Nikolas Freitas Mr Nik

Reputation: 421

If anyone wants to get the path from class controller @RequestMapping you can try read the annotation directly:

    private static String getControllerPath() {
        val annotation = IoaIntegrationController.class.getAnnotation(RequestMapping.class);
        val pathList = Objects.requireNonNullElse(annotation.value(), annotation.path());
        return pathList[0];
    }

Upvotes: 0

Assen Kolov
Assen Kolov

Reputation: 4393

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

Upvotes: 2

kryger
kryger

Reputation: 13181

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)

Upvotes: 3

Related Questions