使用場景
- 需要對項目中的所有輸入進行前後空格的過濾
- 替換一些特殊字符的輸入
- 解密一些關鍵性字段
- 注入一些參數在請求方法的時候
- 返回參數統一處理,如果後臺返回空,統一返回成功信息
- 身份證等特殊字符統一做 * 號處理等
code
主要就是用到了 RequestBodyAdvice
和 ResponseBodyAdvice
兩個接口和一個註解 @ControllerAdvice
- 請求參數去空格
package com.sanri.test.testmvc.config;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.Iterator;
import java.util.Map;
/**
* 去掉前後空格和特殊字符
*/
@Slf4j
@ControllerAdvice
public class CustomRequestBodyAdvice 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(filterDangerString(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();
}
private String filterDangerString(String value) {
if(StringUtils.isBlank(value))return value;
value = value.replaceAll(";", ";");
value = value.replaceAll("'", "‘");
value = value.replaceAll("<", "《");
value = value.replaceAll(">", "》");
value = value.replaceAll("\\(", "(");
value = value.replaceAll("\\)", ")");
value = value.replaceAll("\\?", "?");
return value;
}
}
}
- 使用 ResponseBodyAdvice 處理返回空返回
package com.sanri.test.testmvc.config;
import com.alibaba.fastjson.JSONObject;
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.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Executable;
import java.lang.reflect.Type;
/**
* 可以定義空返回的時候返回正確的信息,如成功信息
*/
@RestControllerAdvice
public class CustomResponseBodyAdvice implements ResponseBodyAdvice {
@Override
public boolean supports(MethodParameter returnType, Class converterType) {
return true;
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
Executable executable = returnType.getExecutable();
AnnotatedType annotatedReturnType = executable.getAnnotatedReturnType();
Type type = annotatedReturnType.getType();
return JSONObject.parseObject("{\"result\":0}");
}
}
項目代碼
我弄了一個例子代碼,關於 java 中每個工具的使用,如 rabbitmq
,mysql
,mybatis
,springboot
,springmvc
可以方便初學者,更方便我自己隨時取用,github 地址
https://gitee.com/sanri/example
sanri-tools 工具
推廣下我的小工具,很實用的解決項目中的一些麻煩的事情,歡迎來 github 點星,fork
https://gitee.com/sanri/sanri-tools-maven