java

位置:IT落伍者 >> java >> 浏览文章

Struts里提交中文表单到ActionForm的乱码问题


发布日期:2022年09月20日
 
Struts里提交中文表单到ActionForm的乱码问题

由于Struts框架直接把表单数据发送给了ActionForm所以这里面没有对HttpRequestServlet进行SetCharacterEncoding所以默认是按照ISO(参见Tomcat 源代码中的orgnnectorHttpRequestBase中的protected void parseParameters()方法)

解决的方法就是在表单提交到ActionForm之前对request进行编码

第一种方法就是写一个过滤器对所有请求进行过滤

过滤器代码

package ricohgtisothersprofilefilters;

import javaioIOException;

import javaxservletFilter;

import javaxservletFilterChain;

import javaxservletFilterConfig;

import javaxservletServletException;

import javaxservletServletRequest;

import javaxservletServletResponse;

public class SetCharacterEncodingFilter implements Filter {

private String encoding;

public void init(FilterConfig filterConfig) throws ServletException {

// TODO Autogenerated method stub

thisencoding=filterConfiggetInitParameter(encoding);

}

public void doFilter(ServletRequest request ServletResponse response

FilterChain chain) throws IOException ServletException {

// TODO Autogenerated method stub

requestsetCharacterEncoding(thisencoding);

chaindoFilter(requestresponse);

}

public void destroy() {

// TODO Autogenerated method stub

}

}

配置文件webxml

<filter>

<filtername>SetCharacterEncodingFilter</filtername>

<filterclass>ricohgtisothersprofilefiltersSetCharacterEncodingFilter</filterclass>

<initparam>

<paramname>encoding</paramname>

<paramvalue>utf</paramvalue>

</initparam>

</filter>

<filtermapping>

<filtername>SetCharacterEncodingFilter</filtername>

<urlpattern>/*</urlpattern>

</filtermapping>

第二种方法是替换默认的控制器orgapachestrutsactionActionServlet

子类代码

package ricohgtintrollers;

import javaioIOException;

import javaxservletServletException;

import javaxservlethttpHttpServletRequest;

import javaxservlethttpHttpServletResponse;

import orgapachestrutsactionActionServlet;

public class SetEncodingActionServlet extends ActionServlet {

protected void process(HttpServletRequest request HttpServletResponse response) throws IOException ServletException {

// TODO Autogenerated method stub

String encoding = getInitParameter(encoding);

requestsetCharacterEncoding(encoding);

superprocess(request response);

}

}

配置文件webxml

<servlet>

<servletname>testAction</servletname>

<servletclass>ricohgtintrollersSetEncodingActionServlet</servletclass>

<initparam>

<paramname>config</paramname>

<paramvalue>/WEBINF/strutsconfigxml</paramvalue>

</initparam>

<initparam>

<paramname>encoding</paramname>

<paramvalue>utf</paramvalue>

</initparam>

<loadonstartup></loadonstartup>

</servlet>

<servletmapping>

<servletname>testAction</servletname>

<urlpattern>*testdo</urlpattern>

</servletmapping>

此例凡是通过*testdo来请求的数据都会经过参数encoding设定的值来编码

上一篇:基于hibernate的开源通用查询框架-bba96

下一篇:检测代码是否有Junit Test Class的小功能