方案一
AdviceAdapter+Interceptor
get使用拦截器校验,post请求使用
@ControllerAdvice
https://cloud.tencent.com/developer/article/1516443
package com.shendi.dolphin.common.interceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;
import java.lang.reflect.Type;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ControllerAdvice
@Slf4j
public class MyRequestBodyAdviceAdapter extends RequestBodyAdviceAdapter {
private static final Pattern FULL_CHARACTER = Pattern.compile("[^\\x00-\\xff]");
@Override
public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
return true;
}
@Override
public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
if (body == null) {
return true;
}
log.info("POST请求体:{}", body);
if (StringUtils.isEmpty(body)) {
return true;
}
Matcher matcher = FULL_CHARACTER.matcher(body.toString());
Assert.isTrue(!matcher.find(), "请使用半角输入法输入,重新提交");
return super.afterBodyRead(body, inputMessage, parameter, targetType, converterType);
}
}
package com.shendi.dolphin.common.interceptor;
import com.shendi.dolphin.common.wrapper.BodyReaderWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Slf4j
public class CharacterInterceptor implements HandlerInterceptor {
private static final Pattern FULL_CHARACTER = Pattern.compile("[^\\x00-\\xff]");
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.info("-----------------------进入字符编码拦截器--------------------------");
// String contentType = request.getContentType();
String method = request.getMethod();
if ("GET".equals(method)) {
//获取请求参数
String queryString = request.getQueryString();
log.info("GET请求参数:{}", queryString);
if (StringUtils.isEmpty(queryString)) {
return true;
}
Matcher matcher = FULL_CHARACTER.matcher(queryString);
Assert.isTrue(!matcher.find(), "请使用半角输入法输入,重新提交");
}
return true;
}
}
方案二
Wrapper+Filter+Interceptor
标签:编码,拦截器,return,字符,springframework,util,org,import From: https://www.cnblogs.com/xgdzyg/p/16899729.html