1 Requirements
After each request succeeds, the response format returned by the background is consistent, for example:
2 Creating a View model
The model is used to format the response data
Package Cn.xiangxu.springboottest.model.dataViewModel; Import Lombok. Data; @Datapublicclass resultviewmodel<t> { private Integer Code; Private String message; Private T data;}
3 Creating a View Model tool class
The tool class instantiates the view model class according to the parameters passed in
Packagecn.xiangxu.springboottest.utils;ImportCn.xiangxu.springboottest.model.dataViewModel.ResultViewModel;/*** Response Data Encapsulation class*/ Public classResultviewmodelutil {/*** Request Success Method *@paramObject Response Data *@returnView Model Instances*/ Public StaticResultviewmodel Success (Object object) {Resultviewmodel Resultviewmodel=NewResultviewmodel (); Resultviewmodel.setcode (0); Resultviewmodel.setmessage ("Request Succeeded"); Resultviewmodel.setdata (object); returnResultviewmodel; } /*** Request Success Method *@returnView Model Instances*/ Public StaticResultviewmodel Success () {returnSuccessNULL); } /*** Request Failed Method 01 (The known exception caught) *@paramCode Exception number *@paramMessage Exception information *@returnView Model Instances*/ Public StaticResultviewmodel Error (Integer code, String message) {Resultviewmodel Resultviewmodel=NewResultviewmodel (); Resultviewmodel.setcode (code); Resultviewmodel.setmessage (message); Resultviewmodel.setdata (NULL); returnResultviewmodel; } /*** Request Failed Method 02 (System exception) *@returnView Model Instances*/ Public StaticResultviewmodel error () {Resultviewmodel Resultviewmodel=NewResultviewmodel (); Resultviewmodel.setcode (-1); Resultviewmodel.setmessage ("System Exception"); Resultviewmodel.setdata ("In-system maintenance ..."); returnResultviewmodel; }}
View Code
4 Using the View Model tool class to return formatted JSON data to the foreground
PackageCn.xiangxu.springboottest.controller;ImportCn.xiangxu.springboottest.model.dataViewModel.ResultViewModel;ImportCn.xiangxu.springboottest.service.GirlService;ImportCn.xiangxu.springboottest.utils.ResultViewModelUtil;Importlombok.extern.slf4j.Slf4j;Importorg.springframework.web.bind.annotation.GetMapping;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RestController;ImportJavax.annotation.Resource; @RestController @requestmapping (Value= "/girl") @Slf4j Public classGirlcontroller {@Resource (name= "Girlservice") PrivateGirlservice Girlservice; @GetMapping PublicResultviewmodel Test () {Log.info ("Hello boy."); returnResultviewmodelutil.success ("Response data");//return Resultviewmodelutil.success (Girlservice.findallgirl ()); }}
View Code
SPRINGBOOT06 Unified Response Format