Search code examples
javascriptajaxspringspring-restcontroller

Spring RequestMapping on Root


I am new to Spring and have a little problem with API.

My Spring-Controller

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

  @RequestMapping(value = "/", produces = 
  MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
  public ResponseEntity<Page<User>> getAll(
    @RequestParam("param") boolean param, HttpServletResponse response) {
    /* DO STUFF */
  }
}

How my JavaScript currently works (w

http.get("/api/user/?param=test");

How I would like to use it

http.get("/api/user?param=test");

But if there is no parameter I still would like to be able to call

http.get("/api/user/");

As you can see I would like to get ride of the "extra / ". Is there a way to do this?


Solution

  • You can try this :

    @RequestMapping(value = { "", "/" }, produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET) 
    public ResponseEntity<Page<User>> getAll(@RequestParam(value = "param", required = false) boolean param, HttpServletResponse response) {
        /* DO STUFF */ 
    }
    

    With the required=false, you'll be able to hit this method with /api/user/ (without parameter).

    You can also create two different handlers (one to support param parameter and another to handle /).