參數轉發: 對@RequestBody 接收的數據攔截進行解密(或其他處理)

一.使用場景-參數轉發

1.springMVC 中使用註解@RequestBody 接收接口參數;

2.大批量接口需要對請求參數做同個或相似處理,,比如對接收參數做解密之類;

二.實現

實現 RequestBodyAdvice 接口,重寫beforeBodyRead函數;

三.demo

解密

@Component
@ControllerAdvice(basePackages = "demo.controller")//controller所在包
public class DemoRequestBody implements RequestBodyAdvice {

    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType)
            throws IOException {
        // 提取數據
        InputStream is = inputMessage.getBody();
        byte[] data = new byte[is.available()];
        is.read(data);
        //轉數據類型
        ObjectMapper mapper = new ObjectMapper();
        Map<String, String> m = mapper.readValue(new String(data), Map.class);
        // 解密 / 其他數據處理
        byte[] respData = // TODO;
        // 回傳處理後的數據
        return new DecodedHttpInputMessage(inputMessage.getHeaders(), new ByteArrayInputStream(respData));
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }

    static class DecodedHttpInputMessage implements HttpInputMessage {

        HttpHeaders headers;
        InputStream body;

        public DecodedHttpInputMessage(HttpHeaders headers, InputStream body) {
            this.headers = headers;
            this.body = body;
        }

        @Override
        public InputStream getBody() throws IOException {
            return body;
        }

        @Override
        public HttpHeaders getHeaders() {
            return headers;
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章