处理多个HTTP响应并在单个方法中一次性返回它们。

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

handling multiple http responses and returning them at once in single method

问题

我有控制器和服务类,其中有以下方法

服务类

public ResponseEntity methodA(Model model) {
 if(model.contains("val1")) {
  service(val1);
 }
 if(model.contains("val2")) {
  service(val2);
 }
 if(model.contains("val3")) {
  service(val3);
 }

}
public ResponseEntity<ResponseModel> service(String val) {
 // 处理 API 调用的一些逻辑
}

我从控制器类中调用了methodA方法,该方法期望返回响应。

所以我的问题是,我可以在执行三个 if 块后一次性返回多个响应,而不是逐个返回吗?

英文:

I have controller and service class which have these methods

service class

public ResponseEntitiy methodA(Model model) {
 if(model.contains(&quot;val1&quot;)) {
  service(val1);
 }
 if(model.contains(&quot;val2&quot;)) {
  service(val2);
 }
 if(model.contains(&quot;val3&quot;)) {
  service(val3);
 }

}
public ResponseEntity&lt;ResponseModel&gt; service(String val) {
 // some logic to handle api calls
}

I called methodA from controller class which expect Response.

So my question is , Can I return multiple responses all together rather returning one by one after execute three if blocks ?

答案1

得分: 1

在Java中,从一个方法中你只能返回一个值。所以你不能从一个方法中处理多个响应。

代替方法,你可以返回一个响应的列表/映射或自定义对象。

所以代码可以看起来像这样:

public List<ResponseEntity> methodA(Model model) {

    List<ResponseEntity> result = new ArrayList();

    if(model.contains("val1")) {
        result.add(service(val1));
    }

    if(model.contains("val2")) {
        result.add(service(val2));
    }

    if(model.contains("val3")) {
        result.add(service(val3));
    }

    return result;
}
英文:

In java - from one method you can return one value.
So simply you can't handle multiple response from one method.

Instead of it you can return list/map or custom object of response from method.

So code can look like:

public List&lt;ResponseEntitiy&gt; methodA(Model model) {

    List&lt;ResponseEntitiy&gt; result = new ArrayList();

    if(model.contains(&quot;val1&quot;)) {
        result.add(service(val1));
    }

    if(model.contains(&quot;val2&quot;)) {
        result.add(service(val2));
    }

    if(model.contains(&quot;val3&quot;)) {
        result.add(service(val3));
    }

    return result;
}

huangapple
  • 本文由 发表于 2020年9月6日 22:27:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/63765216.html
匿名

发表评论

匿名网友

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

确定