在我的工程里,所有jsp页面,数据库全部用的utf-8格式,当提交表单时获得的数据出现乱码。经过上网查资料得到几种方法,但试过了都没有用:
由于Struts框架直接把表单数据发送给了ActionForm,所以这里面没有对HttpRequestServlet进行SetCharacterEncoding,所以默认是按照ISO-8859-1(参见Tomcat 源代码中的org.apache.catalina.connector.HttpRequestBase中的protected void parseParameters()方法),
解决的方法,就是在表单提交到ActionForm之前对request进行编码。
1:在表单提交到ActionForm之前对request进行编码。写一个过滤器,对所有请求进行过滤。
修改tomcat中的server.xml,找到端口配置的位置,加上一行:URIEncoding="UTF-8"
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" URIEncoding="UTF-8"/>
package com.first.struts.filters;
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 SetCharacterEncodingFilter implements Filter {
private String encoding;
private FilterConfig filterConfig = null;
public void destroy() {
this.encoding = null;
this.filterConfig = null;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding(this.encoding);
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
this.encoding = filterConfig.getInitParameter("encoding");
}
}
配置文件web.xml
<filter>
<filter-name>Set Character Encoding</filter-name>
<filter-class>com.first.struts.filters.SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>GBK</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Set Character Encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2:替换默认的控制器org.apache.struts.action.ActionServlet
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionServlet;
public class SetEncodingActionServlet extends ActionServlet {
protected void process(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
// TODO Auto-generated method stub
String encoding = getInitParameter("encoding");
request.setCharacterEncoding(encoding);
super.process(request, response);
}
}
配置文件web.xml
<servlet>
<servlet-name>testAction</servlet-name>
<servlet-class>jp.co.ricoh.gtis.others.profile.controllers.SetEncodingActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>testAction</servlet-name>
<url-pattern>*.testdo</url-pattern>
</servlet-mapping>
此例,凡是通过*.testdo来请求的数据,都会经过参数encoding设定的值来编码。
试过以上两种方法,发现还是会出现乱码。
想试试看把utf-8改成GBK格式,调试,成功。
我想struts1.2对utf-8是不是不太支持。
具体的还是在以后的学习过程中探讨吧。