@GetMapping and @GetMapping("/{id}") always return @GetMapping("/{id}")

Viewed 7140

I have two methods @GetMapping and @GetMapping("/{id}")

@RestController("/user"){
public class UserRestController {

@GetMapping
public ResponseData get() {
      ...........
    return responseData;
}

@GetMapping("/{id}")
public ResponseData getUser(@PathParam("id") Long id) {
    ResponseData responseData = new ResponseData();
      ...........
    return responseData;
}

When I hit a URL http://localhost:8080/user I took I @GetMapping("/{id}") method because it takes id null, how can I solve this issue?

2 Answers

You are mixing up PathParam with PathVariable.

In your example, I think what you need is the PathVariable. Moreover, you can remove the name field, since the parameter's name is the same: id.

Here's the updated code:

@GetMapping("/{id}")
public ResponseData getUser(@PathVariable Long id) {
   ...
}

Also, what you are looking for to define your user mappings under the same controller, is the RequestMapping annotation:

@RestController
@RequestMapping("/user")
public class UserRestController {
    ...
}

you can use this method

` @GetMapping("/")

public ResponseData getUser(@RequestParam Long id) { ResponseData responseData = new ResponseData();

.......

return responseData; }`

Related