@ RestController中的动态@RequestParam

问题描述 投票:0回答:2

我有一个控制器:

@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();
  }
}

它成功处理了这样的请求,例如:

GET:    /customers/

而且我想通过一些参数吸引用户。例如,电子邮件:

GET:   /customers?email=someemail@gmail.

我尝试过:

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

并且预期会收到异常,因为“ /”已经映射到getAll-class上。有什么办法可以解决这个问题?

java spring rest spring-restcontroller http-request-parameters
2个回答
0
投票
@GetMapping
public Object get((@RequestParam(value = "email", required = false) String email) {
    if (email != null && !email.isEmpty()) { 
     return super.getByEmail(email);
    } else {
      return service.getAll();
    }  
}

0
投票

您必须修改当前的

@GetMapping
public List<User> getAll() {
    return service.getAll();
  }
}
如果要保持URL映射不变,请使用

方法并添加电子邮件作为请求参数。因此它看起来像:

@GetMapping
public List<User> getAll(@RequestParam(value = "email", required = false) String email) {
    if (!StringUtils.isempty(email)) {
        return super.getByEmail(email);
    } else {
        return service.getAll();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.