1.使用HttpServletRequestWrapper重写参数
注意重写getParameterNames和getParameter方法
package com.kittlen.cloud.filter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import util.StringUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
/**
* @author kittlen
* @version 1.0
* @date 2021/8/13 0013
*/
public class RequestParameterWrapper extends HttpServletRequestWrapper {
private Logger log = LoggerFactory.getLogger(RequestParameterWrapper.class);
private Map<String, String[]> params = new HashMap<String, String[]>();
private String thisCharacterEncoding;//参数新字符编码
private String oldCharacterEncoding;//参数原字符编码
boolean isPost;//判断请求是否是post请求
public boolean isPost() {
return isPost;
}
public void setPost(boolean post) {
isPost = post;
}
public String getOldCharacterEncoding() {
return oldCharacterEncoding;
}
public void setOldCharacterEncoding(String oldCharacterEncoding) {
this.oldCharacterEncoding = oldCharacterEncoding;
}
public String getThisCharacterEncoding() {
return thisCharacterEncoding;
}
public void setThisCharacterEncoding(String thisCharacterEncoding) {
this.thisCharacterEncoding = thisCharacterEncoding;
}
public RequestParameterWrapper(HttpServletRequest request) {
super(request);
thisCharacterEncoding = StringUtil.isEmpty(getCharacterEncoding()) ? "UTF-8" : getCharacterEncoding();
isPost = request.getMethod().toUpperCase().equals("POST");
addParametersByArray(request.getParameterMap());
}
private void addParametersByArray(Map<String, String[]> extraParams) {
for (Map.Entry<String, String[]> entry : extraParams.entrySet()) {
addParameter(entry.getKey(), entry.getValue());
}
}
public RequestParameterWrapper(HttpServletRequest request, Map<String, Object> extraParams) {
this(request);
addParameters(extraParams);
}
public void addParameters(Map<String, Object> extraParams) {
for (Map.Entry<String, Object> entry : extraParams.entrySet()) {
addParameter(entry.getKey(), entry.getValue());
}
}
/**
* 重写getParameter,代表参数从当前类中的map获取
*
* @param name
* @return
*/
@Override
public String getParameter(String name) {
String[] values = params.get(name);
if (values == null || values.length == 0) {
return null;
}
return values[0];
}
/**
* 同上
*
* @param name
* @return
*/
@Override
public String[] getParameterValues(String name) {
return params.get(name);
}
/**
* 添加参数
*
* @param name
* @param value
*/
public void addParameter(String name, Object value) {
if (value != null) {
if (value instanceof String[]) {
if (isPost) {
for (int i = 0; i < ((String[]) value).length; i++) {
((String[]) value)[i] = toCharse(((String[]) value)[i], thisCharacterEncoding);
}
}
params.put(name, (String[]) value);
} else if (value instanceof String) {
if (isPost) {
params.put(name, new String[]{toCharse((String) value, thisCharacterEncoding)});
}
params.put(name, new String[]{(String) value});
} else {
if (isPost) {
params.put(name, new String[]{toCharse(String.valueOf(value), thisCharacterEncoding)});
}
params.put(name, new String[]{String.valueOf(value)});
}
}
}
@Override
public Map<String, String[]> getParameterMap() {
return this.params;
}
/**
* 重写该方法,spring参数注入时才能将自定义的参数也进行绑定
*
* @return
*/
@Override
public Enumeration<String> getParameterNames() {
return Collections.enumeration(this.params.keySet());
}
public String toCharse(String str, String charset) {
if (StringUtil.isEmpty(str)) {
return "";
}
try {
if (StringUtil.isNotEmpty(oldCharacterEncoding)) {
str = new String(str.getBytes(oldCharacterEncoding), charset);
return str;
}
if (str.equals(new String(str.getBytes("ISO-8859-1"), "ISO-8859-1"))) {
oldCharacterEncoding = "ISO-8859-1";
str = new String(str.getBytes("ISO-8859-1"), charset);
return str;
}
if (str.equals(new String(str.getBytes("GB2312"), "GB2312"))) {
oldCharacterEncoding = "GB2312";
str = new String(str.getBytes("GB2312"), charset);
return str;
}
if (str.equals(new String(str.getBytes("GBK"), "GBK"))) {
oldCharacterEncoding = "GBK";
str = new String(str.getBytes("GBK"), charset);
return str;
}
} catch (Exception e) {
log.error("调用方法: {} 时,参数编码转换异常,异常为:{}", getServletPath(), e.getMessage());
}
return str;
}
}
2.设置过滤器
package com.kittlen.cloud.filter;
import org.springframework.core.annotation.Order;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.CharacterEncodingFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @author kittlen
* @version 1.0
* @date 2021/7/29 0029
*/
@WebFilter(urlPatterns = "/*")
@Order(1)
public class MyCharacterEncodingFilter extends CharacterEncodingFilter {
//不需要进行处理的接口地址
private static List<String> WhiteUrlList = Stream.of("/health/**").collect(Collectors.toList());
private static AntPathMatcher antPathMatcher = new AntPathMatcher();
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
boolean isWhiteUrl = false;
for (int i = 0; i < WhiteUrlList.size(); i++) {
if (antPathMatcher.match(WhiteUrlList.get(i), request.getServletPath())) {
isWhiteUrl = true;
break;
}
}
if (!isWhiteUrl) {
Map<String, Object> map = addAttribute(request);
RequestParameterWrapper requestParameterWrapper = new RequestParameterWrapper(request, map);
String characterEncoding = request.getCharacterEncoding();
requestParameterWrapper.setCharacterEncoding(characterEncoding == null ? "UTF-8" : characterEncoding);
response.setCharacterEncoding(characterEncoding == null ? "UTF-8" : characterEncoding);
super.doFilterInternal(requestParameterWrapper, response, filterChain);
} else {
super.doFilterInternal(request, response, filterChain);
}
}
public Map<String, Object> addAttribute(HttpServletRequest request) {
Map<String, Object> map = new HashMap<>();
map.put("author", request.getHeader("kittlen"));
return map;
}
}