SpringMVC參數統一處理

項目中遇到有些用戶不小心輸入空格,導致校驗時,出現校驗失敗的現場,爲此,寫一個攔截器統一處理下入參。

/**
 * 去掉前後空格和特殊字符
 *
 * @author yupeng
 */
@Slf4j
@ControllerAdvice
public class OAuth2RequestBodyAdvice implements RequestBodyAdvice {
    @Override
    public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return body;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
        return new CustomHttpInputMessage(httpInputMessage);
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return body;
    }

    class CustomHttpInputMessage implements HttpInputMessage {
        private HttpInputMessage origin;

        public CustomHttpInputMessage(HttpInputMessage httpInputMessage) {
            this.origin = httpInputMessage;
        }

        @Override
        public InputStream getBody() throws IOException {
            HttpHeaders headers = origin.getHeaders();
            InputStream body = origin.getBody();

            // 空參,get 請求,流爲空,非 application/json 請求,不處理參數
            MediaType contentType = headers.getContentType();
            if (contentType == null) {
                return body;
            }
            if (!contentType.isCompatibleWith(MediaType.APPLICATION_JSON)) {
                return body;
            }
            if (body == null) {
                return body;
            }
            String params = IOUtils.toString(body, "utf-8");
            if (StringUtils.isBlank(params)) {
                return body;
            }

            // 正式過濾 json 參數
            Object parse = JSON.parse(params);
            if (parse instanceof JSONArray) {
                JSONArray jsonArray = (JSONArray) parse;
                trimJsonArray(jsonArray);
            } else if (parse instanceof JSONObject) {
                trimJsonObject((JSONObject) parse);
            } else {
                log.error("參數不支持去空格:" + parse + " contentType:" + contentType);
            }
            return IOUtils.toInputStream(JSON.toJSONString(parse, SerializerFeature.WriteMapNullValue), "UTF-8");
        }

        private void trimJsonObject(JSONObject jsonObject) {
            Iterator<Map.Entry<String, Object>> iterator = jsonObject.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> next = iterator.next();
                String key = next.getKey();
                Object value = next.getValue();
                if (value instanceof JSONArray) {
                    trimJsonArray((JSONArray) value);
                } else if (value instanceof JSONObject) {
                    trimJsonObject((JSONObject) value);
                } else if (value instanceof String) {
                    String trimValue = StringUtils.trim(ObjectUtils.toString(value));
                    next.setValue(trimValue);
                }
            }
        }

        private void trimJsonArray(JSONArray jsonArray) {
            for (int i = 0; i < jsonArray.size(); i++) {
                Object object = jsonArray.get(i);
                if (object instanceof JSONObject) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    trimJsonObject(jsonObject);
                } else if (object instanceof String) {
                    String trimValue = StringUtils.trim(ObjectUtils.toString(object));
                    jsonArray.set(i, trimValue);
                }

            }
        }

        @Override
        public HttpHeaders getHeaders() {
            return origin.getHeaders();
        }

    }
}

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