英文:
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 filledMap
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();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论