使用拦截器或者切面什么的时候,会获取request里的参数,当参数是中文的时候就容易出现中文乱码
因为传输的时候使用的字符编码是 iso8859-1,所以需要转换一下
request.getParameter()获取单个参数的值,而getRequestParamsMap则是获取到的参数转换成map类型
首先是要获取到request
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
得到request后进行处理,得到map,方法如下
方法一:返回Map<String, String>
public static Map<String, String> getRequestParamsMap(HttpServletRequest request) {
Map<String, String> params = new HashMap<String, String>();
Map requestParams = request.getParameterMap();
for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
String name = (String) iter.next();
String[] values = (String[]) requestParams.get(name);
String valueStr = "";
for (int i = 0; i < values.length; i++) {
valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
}
try {
//将获取到的value值字符编码进行转换
valueStr = new String(valueStr.getBytes("iso8859-1"), request.getCharacterEncoding());
} catch (Exception e) {
logger.error(HttpHelper.class + "字符转化失败!", e);
}
// 乱码解决,这段代码在出现乱码时使用。
params.put(name, valueStr);
}
return params;
}
方法二:返回Map<String, String[]>
/**
* 乱码解决,这段代码在出现乱码时使用
* @param request
* @return
*/
public static Map<String, String[]> myGetRequestParamsMap(HttpServletRequest request) {
Map<String, String[]> params = new HashMap<String, String[]>();
Map requestParams = request.getParameterMap();
for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
String name = (String) iter.next();
String[] values = (String[]) requestParams.get(name);
String valueStr = "";
String[] valueArr = new String[]{};
for (int i = 0; i < values.length; i++) {
valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
}
try {
//将获取到的value值字符编码进行转换
valueStr = new String(valueStr.getBytes("iso8859-1"), request.getCharacterEncoding());
// System.out.println("request.getCharacterEncoding()-----"+request.getCharacterEncoding());
//将转换后的拼接字符串拆分成数组
valueArr = valueStr.split(",");
} catch (Exception e) {
logger.error("字符转化失败!", e);
}
params.put(name, valueArr);
}
return params;
}