如何在将对象列表作为响应返回时添加成功/错误标志

时间:2017-08-21 14:22:11

标签: java spring-mvc

enter image description here enter image description here

 @RequestMapping(value = "/SubmitStep1.json", method = RequestMethod.POST,  headers = "Accept=application/json,application/xml")
        @ResponseBody
        public List<ShopDetails> showShopList(@RequestBody ShopDetails shopDetails)throws Exception{
            List<ShopDetails> shopDetailsList=new ArrayList<ShopDetails>();
            shopDetailsList=dbq.getShopDetails(shopDetails);
            return shopDetailsList;
        }

在上面的代码中,我将返回商店列表,其中包含每个商店的详细信息。

所以,我的问题是,如果我得到商店列表,我可以在返回时添加成功/错误消息。

1 个答案:

答案 0 :(得分:5)

如上所述@araknoid - 您可以创建包装器:

public class ShopListResponse {

private List<ShopDetails> shopList;

private String message;

public ShopListResponse (List<ShopDetails> shopList, String message){
this.shopList = shopList;
this.message = message;
}

// getters and setters
}

在您的控制器类中:

@RequestMapping(value = "/SubmitStep1.json", method = RequestMethod.POST,  headers = "Accept=application/json,application/xml")
@ResponseBody
public ResponseEntity<ShopListResponse> showShopList(@RequestBody ShopDetails shopDetails)throws Exception{

List<ShopDetails> shopDetailsList = dbq.getShopDetails(shopDetails);
return new ResponseEntity<>(new ShopListResponse(shopDetailsList, "Success or error message"), HttpStatus.OK); 
}

如果您想要返回错误 - 您可以返回HttpStatus.NOT_FOUND,或者只返回HttpStatus.OK并发送错误消息 - 它取决于您的方法。

此控制器结果:enter image description here