接手一个项目,里采用的spring mvc。
其中有个controller里的接口方法的参数总算是乱码:
param=={identityId:"50022619960912522X",name:"鏇惧皬姊?"}
一开始我以为是web.xml的编码过滤器没有配置,我看了下配置了,是配置无误的。
<!-- Character Encoding filter -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
后来我怀疑是参数没声明数据类型,我加上了,还是有问题,
contentType : 'application/json;charset=utf-8',
后来我怀疑是我的web项目和controller这个类文件的编码不是utf-8,经过检测,都是utf-8没问题。
后来终于发现是之前的序猿写下了坑爹的代码:
/*
* 流获取参数
*/
public static String getParams(HttpServletRequest request) {
String param = "";
try {
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
// 将资料解码
String reqBody = sb.toString();
param = URLDecoder.decode(reqBody, HTTP.UTF_8);
System.out.println("param==" + param);
} catch (Exception e) {
// TODO Auto-generated catch block
return "";
}
return param;
}
而这个接口的参数类型是json,是通过这个方法获取的,这个方法的这句:
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
明显没给InputStreamReader指定编码啊!InputStreamReader是从字节流转换成字符流,不指定编码不乱码才怪呢。
还有处理post数据你用URLDecoder.decode解码不是来搞笑的吗?
修改之后无乱码问题:
/*
* 流获取参数
*/
public static String getParams(HttpServletRequest request) {
String param = "";
try {
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(),"UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
param = sb.toString();
System.out.println("param==" + param);
} catch (Exception e) {
return "";
}
return param;
}