0

I have a controller:

@RestController
@RequestMapping(value = UserRestController.REST_URL, produces = 
MediaType.APPLICATION_JSON_VALUE)
public class UserRestController {

static final String REST_URL = "/customers";

@GetMapping
public List<User> getAll() {
    return service.getAll();
  }
}

It succesfully handle such requests,as:

GET:    /customers/

And I want to get users by some parameters.For example, email:

GET:   /customers?email=someemail@gmail.

I tried:

@GetMapping("/")
public User getByEmail(@RequestParam(value = "email") String email) {
    return super.getByEmail(email);
}

and expectedly I receive an exception, as "/" is already mapped on getAll-class. Is there any ways to solve this problem?

Nicktar
  • 5,548
  • 1
  • 28
  • 43
Jelly
  • 972
  • 1
  • 17
  • 40
  • try this `@GetMapping("/email") public User getByEmail(@RequestParam(value = "email") String email) { return super.getByEmail(email); }` – Rahul Agrawal Feb 19 '20 at 12:36
  • This way is working, but it mapped on /customers/email?email=someemail@gmail. And I need exactly /customers?email=someemail@gmail. – Jelly Feb 19 '20 at 12:42

2 Answers2

2
@GetMapping
public Object get((@RequestParam(value = "email", required = false) String email) {
    if (email != null && !email.isEmpty()) { 
     return super.getByEmail(email);
    } else {
      return service.getAll();
    }  
}
Dinesh Shekhawat
  • 504
  • 6
  • 13
2

You have to modify your current

@GetMapping
public List<User> getAll() {
    return service.getAll();
  }
}

method and add the email as a request parameter if you want to keep the URL mapping the same. So it will look like:

@GetMapping
public List<User> getAll(@RequestParam(value = "email", required = false) String email) {
    if (!StringUtils.isempty(email)) {
        return super.getByEmail(email);
    } else {
        return service.getAll();
    }
}
mherBaghinyan
  • 476
  • 5
  • 13
  • I tried. GET: /customers/ now is workig well. But GE: /customers?email=someemail@gmail.com returns 405 – Jelly Feb 19 '20 at 13:06