Search code examples
javaspring-mvcspring-restcontrollerrequest-mapping

Spring MVC RequestMapping not working on RestController


I want to have a RestController-class with the base-mapping "/user" (so the different functions will have paths like "/user/add", "/user/remove" etc or use POST/GET etc)

This is the part that I don't understand and can't get to work:

@RestController
public class UserController {

  @GetMapping("/user")
  public Response login(Principal principal){
    //some output
  }
}

Expected behavior for this case would be that I can access my output under "/user". This works as expected. Now if I modify it to the following (since all functions in this controller should have a path starting with "/user" this would be cleaner)

@RestController
@RequestMapping("/user")
public class UserController {

  @GetMapping("/")
  public Response login(Principal principal){
    //some output
  }
}

I get a 404-Error page and can't access "/user" anymore All examples I have found use the same syntax (or sometimes @RequestMapping(path="/user") but that didn't work as well) and I don't know why it doesn't work. Can someone tell me where my mistake is?


Solution

  • If you use this code:

    @RestController
    @RequestMapping("/user")
    public class UserController {
    
    @GetMapping("/")
    public Response login(Principal principal){
    //some output
     }
    }
    

    Then your url should have "/" at the end like "http://localhost:8080/user/"

    I would just throw away "/" symbol from @GetMapping("/") and left like this:

    @RestController
    @RequestMapping("/user")
    public class UserController {
    
    @GetMapping
    public Response login(Principal principal){
    //some output
     }
    }
    

    And if you need map get or post you can use like this:

    @RestController
    @RequestMapping("/user")
    public class UserController {
    
    @GetMapping("/add")
    public SampleObj getJson() {
        return new SampleObj();
     }
    }
    

    It should work.