JavaWeb开发中,需要给前端返回的数据加上一些头部的状态信息,来表示请求成功或失败的状态原因
一、数据添加状态信息
1.新建BaseData
public class BaseData<T> { private String returnCode;
private String returnMsg;
private T data;
//其他的get set toString 方法略
}
2.定义工具类:
public final class ReturnInfoUtils {
private ReturnInfoUtils(){}
//返回状态信息
public static final String SUCCESSCODE="100";
public static final String SUCCESSMSG="操作成功";
public static final String FAILCODE="500";
public static final String FAILMSG="操作失败";
}
3.定义注解:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ReturnWrapper { String returnCode() default ReturnInfoUtils.SUCCESSCODE;
String returnMsg() default ReturnInfoUtils.SUCCESSMSG;
}
4.新建类继承AbstractMappingJacksonResponseBodyAdvice
并重写一个切面方法beforeBodyWriteInternal
package com.zpark.tools.interceptor; import com.zpark.response.ReturnDto;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJacksonValue;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.AbstractMappingJacksonResponseBodyAdvice; /**
* @author cosmo
* @Title: CommonWrsControllerAdvice
* @ProjectName
* @Description: TODO
* @date
*/
@RestControllerAdvice
public class CommonWrsControllerAdvice extends AbstractMappingJacksonResponseBodyAdvice {
@Override
protected void beforeBodyWriteInternal(MappingJacksonValue mappingJacksonValue, MediaType mediaType, MethodParameter methodParameter, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
if (methodParameter.getMethod().isAnnotationPresent(RerutnWrapper.class)) {
mappingJacksonValue.setValue(getWrapperResponse(methodParameter,serverHttpRequest, mappingJacksonValue.getValue()));
}
} private ReturnDto getWrapperResponse(MethodParameter returnType, ServerHttpRequest req, Object data) {
ReturnWrapper wrapper=returnType.getMethod().getAnnotation(ReturnWrapper.class);
BaseData = new BaseData();
returnDto.setData(data);
returnDto.setreturnCode(wrapper.ReturnCode());
return returnDto;
}
}
就可以用注解来返回的数据
/**
* 测试.
*
* @return the attachment info
*/
@ResponseBody
@RequestMapping(value = {"test"})
@RestWrapper(msg = ReturnInfoUtils.GETSUCCESS)
public List<Employee> test() {
List<Employee> employeeList=new ArrayList<>();
Employee employee=new Employee();
employee.setName("lisi");
employeeList.add(employee);
return employeeList;
}
返回数据:
{
"returnCode": "SUCCESS",
"returnMsg": "操作成功",
"data": [
{
"name": "lisi"
}
]
}