Spring Boot和Java 8:是否有一种动态构建字符串的方式?

huangapple go评论77阅读模式
英文:

Spring boot and java 8: Is there a way to build a string dynamically?

问题

有没有一种方法在Java 8和/或Spring Boot中动态构建字符串?我正在尝试使用从REST服务调用中接收的参数构建URL,此服务具有多个可选的过滤器,我可以使用伪AI方法,在其中使用多个if-else来验证所有内容,但我认为那不是最好的方法。这个URL是对Jira REST API的调用,因此语法是独特的。

我想避免的是这种情况:

and = ""%20AND%20"";
if (param1 != null) url += param1;
if (param1 != null && param2 != null) url += param1 + and + param2;
if (param1 != null && param2 != null && param3 != null) url += param1 + and + param2 + and + param3;
if (param1 != null && param2 == null && param3 != null) url += param1 + and + param3;

我认为肯定有比验证每个参数10次更好的方法。

英文:

Is there a way to dynamically build a string in java 8 and/or spring boot? I'm trying to build an URL with parameters received from a REST Service call, this service has multiple optional filters, I can use the pseudo-AI method where I validate everything with multiple if-else but I don't think that's the best way to do it. This URL is a called to Jira REST Api so the syntax is something unique.

What I want to avoid is this

and = "\"%20AND%20\"";    
if (param1 != null) url += param1;
if (param1 != null && param2 != null) url += param1 + and + param2;
if (param1 != null && param2 != null && param3 != null) url += param1 + and + param2 + and + param3;
if (param1 != null && param2 == null && param3 != null) url += param1 + and + param3;

I think there must be a better way to do this than validating 10 times each parameter.

答案1

得分: 0

有多种可用的解决方案:

  • 只需使用StringBuilder或简单的字符串连接来构建查询字符串。
  • Spring的UriComponentsBuilder JavaDoc 提供了一种更有结构化的方式来构建查询字符串,对于基于JPA的解决方案可能更加熟悉。
  • 使用RestTemplates 可以传递一个有条件填充的Map,表示您的请求参数。
  • Spring更新的WebClient 类还支持使用像这样的URI构建器设置get请求的参数:
WebClient c = WebClient.create();
c.get().uri(uriBuilder -> uriBuilder
    .queryParam("param1", "value")
    .queryParam("param2", "value2")
    .build()
).retrieve();
英文:

There are various solutions available:

  • just use a StringBuilder or simple string concatenation to build up your query string
  • Springs UriComponentsBuilder JavaDoc provides a more structured way of building a query string and might be more familiar to your JPA based solution
  • using RestTemplates allows to pass a conditionally filled Map representing your request parameters
  • Springs newer WebClient class also supports setting paramters on a get using a uri builder like this:
WebClient c = WebClient.create();
c.get().uri(uriBuilder -> uriBuilder
    .queryParam("param1", "value")
    .queryParam("param2", "value2")
    .build()
).retrieve();

huangapple
  • 本文由 发表于 2020年9月5日 01:54:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/63745951.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定