ltfishie
ltfishie

Reputation: 2987

Set spring mvc request mapping programmatically

In a spring-mvc annotated controller:

@RequestMapping(value = "/my")
public class MyController {
       @RequestMapping(value = "/something")
       public doSomething() {
       }
       public String getPath() {
            return "somethingElse";
       }
}

For Restful service, each resource is usually associated with an class in the domain. For example, for User object, my url for update via POST can be /myapp/user; for SomeOtherData, my url would be /myapp/someother.

I want to be able to determine the url for my Restful service given the Class. I want a way to associate a class to the url without having to keep the association elsewhere.

So, is there a way for me to set the path programmatically by calling a method, say getPath(), with Spring MVC?

Upvotes: 1

Views: 2345

Answers (2)

diafour
diafour

Reputation: 41

1. The best solution for reversing is a centralized router like the one in rails (https://stackoverflow.com/a/12881531/2533287)

2. May be you just need to define path as a constant

@RequestMapping(value = MyController.PATH)
public class MyController {
       public static final String PATH="/my";

       @RequestMapping(value = "/something")
       public doSomething() {
       }
       public static String getPath() {
            return PATH;
       }
}

...

String myControllerUrl = MyController.getPath();

3.

is there a way for me to set the path programmatically by calling a method, say getPath(), with Spring MVC

I don't understand what path you want to set? Path for controller or "String path" variable somewhere else?

Upvotes: 0

nicholas.hauschild
nicholas.hauschild

Reputation: 42849

EDIT: I have changed my answer to show how you could use @PathVariable to emulate a 'setPath()' method.

I don't believe that you can do that, but you can emulate that effect using dynamic path elements.

@RequestMapping(value = "/my")
public class MyController {
    private String supportedPath = "default";

    @RequestMapping(value = "/{aPathElement}")
    public void doSomething(@PathVariable("aPathElement") String elementName) {
        if(elementName.equals(supportedPath) {
            //do something...
        } else {
            //send 404 page not found...
        }
    }

    public void setPath(String newPath) {
        supportedPath = newPath;
    }
}

Upvotes: 1

Related Questions