英文:
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("val1")) {
service(val1);
}
if(model.contains("val2")) {
service(val2);
}
if(model.contains("val3")) {
service(val3);
}
}
public ResponseEntity<ResponseModel> 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<ResponseEntitiy> methodA(Model model) {
List<ResponseEntitiy> 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;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论