1

I am using Spring framework to create api. I want two urls defined at the class level

@RequestMapping({"/jobs","/subs"})

and I want to call method 1 when the url is /host:port/jobs and I want to call method 2 when the url is /host:port/subs

Is there a way to do this ?

I could remove the mapping at the class level and define it on the method level but I do not want to do that as I don't want to have to define the mapping for all the other methods.

1
  • not possible. Define RequestMapping for each method. Commented Oct 25, 2016 at 16:38

3 Answers 3

1

You can use @PathVariable

@RequestMapping(value = "/{whichOne}")
public class someController {
    @RequestMapping
    public ResponseObject someMethod(@PathVariable("whichOne") String whichOne) {
        switch (whichOne) {
            case "jobs":
                return resolveJobs();
            case "subs":
                return resolveSubs();
        }
    }
}

But I don't recommend you to do that. Two methods with two request mappings is correct way to go.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your help but if you use a path variable then you will have issues using HATEOAS Links by calling that method.
1
I don't want to have to define the mapping for all the other methods.

What do you mean? Just like any other class, You can have methods in the controller class which doesn't map to any URL pattern.

I think there is some flaw in the design here. I would rather add this mapping at the method level and have 2 separate methods handle this.

1 Comment

What I meant was that other methods will have partial urls to be appended to the class level url.
1

It is really ugly, but you can do it with this trick:

@Controller
@RequestMapping({ "/jobs", "/subs" })
public class MyController {

    @RequestMapping(method = RequestMethod.GET)
    public String get(HttpServletRequest request) {

        String url = request.getRequestURI().toString();

        if (url.endsWith("jobs")) { // or contains
            return getJobs(request);
        }

        // subs
        return getSubs(request);
    }

    private String getJobs(HttpServletRequest request) {
        [...]
        return "jobs";
    }

    private String getSubs(HttpServletRequest request) {
        [...]
        return "subs";
    }
}

1 Comment

Only problem is that the sub methods have partial urls too. But I will try this with a change of design. Thanks for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.