preface

Since the return JSON API format interface, we need to encapsulate a unified data return format through Java beans to facilitate interaction with front-end conventions.

Status code enumeration ResultCode

package cn.soboys.core.ret;


import lombok.Getter;

/ * * *@author kenx
 * @version 1.0
 * @date2021/6/17 15:35 * Enumeration of response codes corresponding to HTTP status codes */
@Getter
public enum ResultCode {

    SUCCESS(200."Success"),/ / success
    //FAIL(400, "FAIL "),// FAIL
    BAD_REQUEST(400."Bad Request"),
    UNAUTHORIZED(401."Authentication failed"),/ / not certification
    NOT_FOUND(404."Interface does not exist"),// The interface does not exist
    INTERNAL_SERVER_ERROR(500."System busy"),// Server internal error
    METHOD_NOT_ALLOWED(405."Method not allowed"),

    /* Error :1001-1999*/
    PARAMS_IS_INVALID(1001."Invalid parameter"),
    PARAMS_IS_BLANK(1002."Parameter null");
    /* User error 2001-2999*/


    private Integer code;
    private String message;

    ResultCode(int code, String message) {
        this.code = code;
        this.message = message; }}Copy the code

Results the body the Result

package cn.soboys.core.ret;

import lombok.Data;

import java.io.Serializable;

/ * * *@author kenx
 * @version 1.0
 * @date2021/6/17 15:47 * Unified API response result format encapsulation */
@Data
public class Result<T> implements Serializable {

    private static final long serialVersionUID = 6308315887056661996L;
    private Integer code;
    private String message;
    private T data;


    public Result setResult(ResultCode resultCode) {
        this.code = resultCode.getCode();
        this.message = resultCode.getMessage();
        return this;
    }

    public Result setResult(ResultCode resultCode, T data) {
        this.code = resultCode.getCode();
        this.message = resultCode.getMessage();
        this.setData(data);
        return this; }}Copy the code

Response result method utility class

package cn.soboys.core.ret;

/ * * *@author kenx
 * @version 1.0
 * @date2021/6/17 16:30 * Response result returns encapsulation */
public class ResultResponse {
    private static final String DEFAULT_SUCCESS_MESSAGE = "SUCCESS";

    // Return status only
    public static Result success(a) {
        return new Result()
                .setResult(ResultCode.SUCCESS);
    }

    // Successfully return data
    public static Result success(Object data) {
        return new Result()
                .setResult(ResultCode.SUCCESS, data);


    }

    / / fail
    public static Result failure(ResultCode resultCode) {
        return new Result()
                .setResult(resultCode);
    }

    / / fail
    public static Result failure(ResultCode resultCode, Object data) {
        return newResult() .setResult(resultCode, data); }}Copy the code

Custom resolution Controller interception

Annotations @ ResponseResult

package cn.soboys.core.ret;

import java.lang.annotation.*;

/ * * *@author kenx
 * @version 1.0
 * @date2021/6/17 16:43 * The value returned by the unified packaging interface Result */
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ResponseResult {
}

Copy the code

Request to intercept ResponseResultInterceptor

package cn.soboys.core.ret;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/ * * *@author kenx
 * @version 1.0
 * @date2021/6/17 17:10 * Request to intercept */
public class ResponseResultInterceptor implements HandlerInterceptor {

    // Mark the name
    public static final String RESPONSE_RESULT_ANN = "RESPONSE-RESULT-ANN";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // Request method
        if (handler instanceof HandlerMethod) {
            final HandlerMethod handlerMethod = (HandlerMethod) handler;
            finalClass<? > clazz = handlerMethod.getBeanType();final Method method = handlerMethod.getMethod();
            // Determine whether the object is annotated
            if (clazz.isAnnotationPresent(ResponseResult.class)) {
                // Set the return body of this request to wrapper, pass it down, and decide on the ResponseBodyAdvice interface
                request.setAttribute(RESPONSE_RESULT_ANN, clazz.getAnnotation(ResponseResult.class));
                // Whether there are annotations in the method body
            } else if (method.isAnnotationPresent(ResponseResult.class)) {
                // Set the return body of this request to wrapper, pass it down, and decide on the ResponseBodyAdvice interfacerequest.setAttribute(RESPONSE_RESULT_ANN, clazz.getAnnotation(ResponseResult.class)); }}return true; }}Copy the code

Request global resolution of ResponseResultHandler

package cn.soboys.core.ret;

import cn.soboys.core.utils.HttpContextUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;

/ * * *@author kenx
 * @version 1.0
 * @date2021/6/17 16:47 * Global unified response return body processing */
@Slf4j
@ControllerAdvice
public class ResponseResultHandler implements ResponseBodyAdvice<Object> {

    public static final String RESPONSE_RESULT_ANN = "RESPONSE-RESULT-ANN";

    / * * *@param methodParameter
     * @param aClass
     * @returnIf false is returned, the business of the current Advice is not executed
    @Override
    public boolean supports(MethodParameter methodParameter, Class
       > aClass) {
        HttpServletRequest request = HttpContextUtil.getRequest();
        // Determine whether the request has a packing mark
        ResponseResult responseResultAnn = (ResponseResult) request.getAttribute(RESPONSE_RESULT_ANN);
        return responseResultAnn == null ? false : true;
    }

    / * * *@param body
     * @param methodParameter
     * @param mediaType
     * @param aClass
     * @param serverHttpRequest
     * @param serverHttpResponse
     * @returnThe specific business approach to handling the response */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class
       > aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (body instanceof Result) {
            return body;
        } else if (body instanceof String) {
            return JSON.toJSONString(ResultResponse.success(body));
        } else {
            returnResultResponse.success(body); }}}Copy the code

For details, please refer to my chapter. Spring Boot Non-invasive RESTful API interface is returned in JSON format