【问题标题】:Dynamic @RequestParam in @RestController@RestController 中的动态 @RequestParam
【发布时间】:2020-02-19 12:31:25
【问题描述】:

我有一个控制器:

@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 上。 有没有办法解决这个问题?

【问题讨论】:

  • 试试这个@GetMapping("/email") public User getByEmail(@RequestParam(value = "email") String email) { return super.getByEmail(email); }
  • 这种方式可行,但它映射到 /customers/email?email=someemail@gmail。我需要 /customers?email=someemail@gmail.

标签: java spring rest spring-restcontroller http-request-parameters


【解决方案1】:
@GetMapping
public Object get((@RequestParam(value = "email", required = false) String email) {
    if (email != null && !email.isEmpty()) { 
     return super.getByEmail(email);
    } else {
      return service.getAll();
    }  
}

【讨论】:

  • 我试过这个。它为 /customers&email=someemail@gmail.com 返回 404-Error 和 404 - 对于 /customers/
  • 你的意思是 /customers?email=someemail@gmail.com
  • 是的。对不起!我犯了一个错误。当我尝试 /customers&email=someemail@gmail.com 时响应 405
  • 现在工作了吗?我在 @RequestParam 注解中添加了必需的 false
  • 您在@RequestParam 中添加了 required = false?
【解决方案2】:

你必须修改你当前的

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

方法并添加 email 作为请求参数,如果您想保持 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();
    }
}

【讨论】:

  • 我试过了。 GET: /customers/ 现在工作得很好。但通用电气:/customers?email=someemail@gmail.com 返回 405
猜你喜欢
  • 2016-11-22
  • 2021-11-22
  • 2022-01-15
  • 1970-01-01
  • 2015-09-07
  • 1970-01-01
  • 1970-01-01
  • 2016-01-04
  • 1970-01-01
相关资源
最近更新 更多