Tanishq dubey
Tanishq dubey

Reputation: 1542

Call a function by its REST API URL in Spring Boot

I don't know if this is possible directly (of course, there are other, and far messier ways to do this), but I wish to be able to call a function by its URL in Spring Boot.

For example, say I have a @RestController and within that rest controller a function that looks like this:

@RequestMapping(value = "/", produces = "application/json", method = RequestMethod.POST)
public String myRequest(@RequestParam("request") String request) {
    return request;
}

What I would like to be able to do is have a user pass in a relative URL for a different endpoint of my API, and my code will call that portion of the api. For instance:

// Pass in "/otherRequest/SomeInfo"
@RequestMapping(value = "/", produces = "application/json", method = RequestMethod.POST)
public String myRequest(@RequestParam("request") String request) {
    //Goes to the function that handles "/otherRequest/SomeInfo"
    // and returns its value
    return callSomeFunctionByURL(request);
}

I realize that I can parse the string and go through a bunch of conditionals to get my result, but is there a more Springy way of doing this - like by calling callSomeFunctionByURL, or would I just have to do it the old way? (For those wondering why this situation would even happen, this is a theoretical question)

Upvotes: 3

Views: 2595

Answers (2)

Roman C
Roman C

Reputation: 1

Theoretically, you should move your business logic to the service layer to use transactions around them.

In some cases you do some sophisticated logic on the view layer that is possible to use beans that you could create or inject to the controller to use in many controller methods and return results.

If this logic is not handled by the controller classes then it should be moved to another layer called a presentation layer. This layer is not covered by Spring, so you should do it yourself.

Upvotes: 1

Saravana
Saravana

Reputation: 12817

I think you can use redirect and forward

Instead of

return request;

change it to

return "redirect:"+request;

or

return "forward:"+request;

EDIT

return new ModelAndView(request) if the controller is RestController

Upvotes: 0

Related Questions