Spring mvc中統(tǒng)一對ResponseBody進(jìn)行封裝

在一個前后端分離的項(xiàng)目中,需要對后端RestController里返回的ResponseBody進(jìn)行統(tǒng)一的封裝,讓所有的API結(jié)果的都是json對象,帶有是否成功的標(biāo)志位,并且將實(shí)際的數(shù)據(jù)放到j(luò)son的result字段中,例如:

{"result":["age","height"],"success":true}

如果在每個RestController中進(jìn)行封裝,重復(fù)的工作很多,因此需要自動封裝,比如已經(jīng)寫好了如下Controller

@RestController()
@RequestMapping("bar")
public class BarController {

    @GetMapping("foo")
    public List<String> getSessionColumns() {
        List<String> result = new ArrayList<>();
        result.add("age");
        result.add("height");
        return result;
    }
}

自動將結(jié)果封裝為

{"result":["age","height"],"success":true}

一開始試驗(yàn)了AOP,但是發(fā)現(xiàn)總是有ClassCastException的問題,后來又找到了ResponseBodyAdvice,才解決這個問題

public class NovaResponseBodyAdvice implements ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        Map<String, Object> result = new HashMap<>();
        result.put("result", body);
        result.put("success", true);
        return result;
    }

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容