简体   繁体   English

@RestController 中的动态 @RequestParam

[英]Dynamic @RequestParam in @RestController

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.预计我会收到一个异常,因为“/”已经映射到 getAll-class 上。 Is there any ways to solve this problem?有没有办法解决这个问题?

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

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.方法并添加电子邮件作为请求参数,如果您想保持 URL 映射不变。 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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM