使用 ResponseBodyAdvice 攔截Controller方法預設返回引數,統一處理返回值/響應體

YClimb發表於2018-11-01

使用 @ControllerAdvice & ResponseBodyAdvice 攔截Controller方法預設返回引數,統一處理返回值/響應體


1、Controller程式碼

以下是Controller查詢方法原始碼:


/**
 * controller
 *
 * @author yclimb
 * @date 2018/6/29.
 */
@RestController
@RequestMapping("/manage/user")
public class TestController {

    private Logger logger = LoggerFactory.getLogger(TestController.class);
    
    /**
     * 通過會員id獲取會員資訊及詳情
     *
     * @param id 會員id
     * @return app msg
     *
     * @author yclimb
     * @date 2018/6/29
     */
    @GetMapping("/edit/{id}")
    public AppMessage edit(@PathVariable Integer id) {
        if (null == id) {
            return AppMessage.error(-3, "會員ID不能為空");
        }

        // 查詢會員物件
        User user = userService.queryById(id);
        if (user == null) {
            return AppMessage.error(-3, "根據會員ID未查詢到對應會員");
        }

        return AppMessage.success(user);
    }

}
複製程式碼

2、攔截處理器

下面已經封裝好了一個攔截處理類以供參考:

package com.yclimb.test;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
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;

/**
 * 攔截Controller方法預設返回引數,統一處理返回值/響應體
 *
 * @author yclimb
 * @date 2018/6/29
 */
@ControllerAdvice
public class TestResponseBodyAdvice implements ResponseBodyAdvice {

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {

        System.out.println("TestResponseBodyAdvice==>beforeBodyWrite:" + o.toString() + ","
                + methodParameter);
        return o;
    }


    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }
}


複製程式碼

3、測試方法

Controller:

TestController

ResponseBodyAdvice:

TestResponseBodyAdvice

結語

到此本文就結束了,關注公眾號檢視更多推送!!!


關注我的公眾號


相關文章