问题描述
在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添加如下代码(不推荐):
<!-- 利用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之后的版本这个方法就失效了。所以最好的办法就是自己写一个过滤器。一个简单的字符过滤器实现如下(推荐):
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"); } }
注意,上面import的javax.servlet 需要你设置好tomcat的lib库才能生效,Project->Properties->Java Build Path->Libraries->Add Libraries -> Server Runtime 找到你的Tomcat服务器确定。
然后你在web.xml中添加下面代码:
<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的缓存)
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="utf-8"/>
3.不建议采用的办法,在接收参数的时候进行转码(虽然能解决问题,但坚决抵制),例如:
String str = new String(request.getParameter("something").getBytes("ISO-8859-1"),"utf-8");