目录[-]
在JSP中使用form表单向后台action中传递中文参数,后台action接收到参数出现中文乱码。JSP页面统一采用了utf-8编码格式。由于struts2默认采用的编码为utf-8,根据官方文档的提示,编码格式改为GBK,就能解决中文乱码。遂改之。但是,改为GBK后仍然出现中文乱码。很是不解(后来去官网查了一下,发现这是个BUG)。
服务器采用tomcat6.0,struts的版本为2.3.12,spring的版本为2.5.6
1.如果你的项目采用了spring,那么请用spring的自带的过滤器来解决这个问题,你只要在web.xml添加如下代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<!-- 利用Spring的Filter解决中文乱码问题 -->
<
filter
>
<
filter-name
>Set Character Encoding</
filter-name
>
<
filter-class
>org.springframework.web.filter.CharacterEncodingFilter</
filter-class
>
<
init-param
>
<
param-name
>encoding</
param-name
>
<
param-value
>utf8</
param-value
>
</
init-param
>
</
filter
>
<
filter-mapping
>
<
filter-name
>Set Character Encoding</
filter-name
>
<
url-pattern
>/*</
url-pattern
>
</
filter-mapping
>
|
但是spring3.x之后的版本这个方法就失效了。所以最好的办法就是自己写一个过滤器。一个简单的字符过滤器实现如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
package
org.felix.common;
import
java.io.IOException;
import
javax.servlet.Filter;
import
javax.servlet.FilterChain;
import
javax.servlet.FilterConfig;
import
javax.servlet.ServletException;
import
javax.servlet.ServletRequest;
import
javax.servlet.ServletResponse;
public
class
CharacterEncodingFilter
implements
Filter {
protected
FilterConfig filterConfig =
null
;
protected
String encoding =
""
;
public
void
destroy() {
filterConfig =
null
;
encoding =
null
;
}
public
void
doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain)
throws
IOException, ServletException {
if
(encoding !=
null
&& !
""
.equals(encoding))
servletRequest.setCharacterEncoding(encoding);
filterChain.doFilter(servletRequest, servletResponse);
}
public
void
init(FilterConfig filterConfig)
throws
ServletException {
this
.filterConfig = filterConfig;
this
.encoding = filterConfig.getInitParameter(
"encoding"
);
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
|
<
filter
>
<
filter-name
>characterEncodingFilter</
filter-name
>
<
filter-class
>org.felix.common.CharacterEncodingFilter</
filter-class
>
<
init-param
>
<
param-name
>encoding</
param-name
>
<
param-value
>UTF-8</
param-value
>
</
init-param
>
</
filter
>
<
filter-mapping
>
<
filter-name
>characterEncodingFilter</
filter-name
>
<
url-pattern
>/*</
url-pattern
>
</
filter-mapping
>
|
2.如果你表单提交采用的是get请求.那么请在tomcat的server.xml中添加URIEncoding="utf-8".(注意添加完后清理掉tomcat的缓存)
3.不建议采用的办法,在接收参数的时候进行转码(虽然能解决问题,但坚决抵制),例如:
1
|
String str =
new
String(request.getParameter(
"something"
).getBytes(
"ISO-8859-1"
),
"utf-8"
) ;
|
------------------------------ -------------- 全文完------------------------------- ------------
出处:http://my.oschina.net/linuxfelix/blog/135854#OSC_h1_1