由于Struts框架直接把表单数据发送给了ActionForm,所以这里面没有对HttpRequestServlet进行 SetCharacterEncoding,所以默认是按照ISO-8859-1(参见Tomcat 源代码中的org.apache.catalina.connector.HttpRequestBase中的protected void parseParameters()方法),
解决的方法,就是在表单提交到ActionForm之前对request进行编码。
第一种方法,就是写一个过滤器,对所有请求进行过滤
过滤器代码:
package jp.co.ricoh.gtis.others.profile.filters;
import javax.servlet.Filter; public class SetCharacterEncodingFilter implements Filter { public void doFilter(ServletRequest request, ServletResponse response, public void destroy() { } } |
配置文件web.xml
<filter> <filter-name>SetCharacterEncodingFilter</filter-name> <filter-class>jp.co.ricoh.gtis.others.profile.filters.SetCharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> |
第二种方法是替换默认的控制器org.apache.struts.action.ActionServlet
子类代码:
package jp.co.ricoh.gtis.others.profile.controllers; import java.io.IOException; import javax.servlet.ServletException; import org.apache.struts.action.ActionServlet; public class SetEncodingActionServlet extends ActionServlet { protected void process(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { } |
配置文件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> |
此例,凡是通过*.testdo来请求的数据,都会经过参数encoding设定的值来编码。