JackTheKnife
JackTheKnife

Reputation: 4144

Spring @RequestMapping annotations to different locations

I'm trying to get something like

http://localhost/ - display Welcome page
http://localhost/api/v1/getUser - do the `getUser` controller part
http://localhost/api/v1/addUser - do the `addUser` controller part

so I have created simple controller for that part

@RestController
public class restController {

    @GetMapping("/")
    public String restAPI() {

            return "Welcome Page";
    }

    @RequestMapping("/api/v1")
    @PostMapping("/addUser")
    @ResponseBody
    public User addUser(@RequestBody User user) {
         //do the stuff
    }


    @RequestMapping("/api/v1")
    @GetMapping("/getUser")
    @ResponseBody
    public User getUser(@RequestBody User user) {
         //do the stuff
    }

what I have got it was only Welcome Page but any of the endpoints were not reachable. When I have removed part responsible for restAPI() I was able to reach those two endpoints.

Is there a way to mix @RequestMapping?

Upvotes: 0

Views: 26

Answers (1)

Chris
Chris

Reputation: 5633

The best solution would be to create two Controllers like this:

@RestController
@RequestMapping("/")
public class HomeController {

    @GetMapping
    public String restAPI() {

        return "Welcome Page";
    }
}

If you send a GET request to http://localhost/ your display the welcome page.

And:

@RestController
@RequestMapping("/api/v1")
public class UserController {

    @PostMapping
    public User addUser(@RequestBody User user) {
         //do the stuff
    }

    @GetMapping
    public User getUser(@RequestBody User user) {
        //do the stuff
    }
}

By send a POST or GET to http://localhost/api/v1/ and create a User or get one.

Upvotes: 1

Related Questions