项目中使用的Framework是Webwork,服务器用的是tomcat5.5.只要统一文件本身编码,charset编码还有webwork.properties中webwork.i18n.encoding=UTF-8的设置,通过表单POST方法提交的中文数据都没有问题,另外项目中间有一些请求是通过Ajax采用Get方法提交的。并且之前由于数据中中文输入项不多,那么我对于提交的数据都用new String(cname.getBytes("ISO-8859-1"), "UTF-8")进行转码,也可以使用。随着要转编码的项越来越多,开始对这种转码的方式感到厌烦,于是想到了从Webwork里面想办法解决。
在FilterDispather.java里找到了这样的一句:
// prepare the request no matter what - this ensures that the proper character encoding
// is used before invoking the mapper (see WW-9127)
DispatcherUtils du = DispatcherUtils.getInstance();
看到DispatcherUtils.java果然Webwork采用的方法和以前解决中文问题用Filter的方式其实一样,无非是先设置request的编码:
public void prepare(HttpServletRequest request, HttpServletResponse response) {
String encoding = null;
if (Configuration.isSet(WebWorkConstants.WEBWORK_I18N_ENCODING)) {
encoding = Configuration.getString(WebWorkConstants.WEBWORK_I18N_ENCODING);
}
Locale locale = null;
if (Configuration.isSet(WebWorkConstants.WEBWORK_LOCALE)) {
locale = LocalizedTextUtil.localeFromString(Configuration.getString(WebWorkConstants.WEBWORK_LOCALE), request.getLocale());
}
if (encoding != null) {
try {
request.setCharacterEncoding(encoding);
} catch (Exception e) {
LOG.error("Error setting character encoding to '" + encoding + "' - ignoring.", e);
}
}
if (locale != null) {
response.setLocale(locale);
}
if (paramsWorkaroundEnabled) {
request.getParameter("foo"); // simply read any parameter (existing or not) to "prime" the request
}
}
原来猜想是webwork会对参数做一些包装和处理,但是只是直接取得parameterMap:
public Map createContextMap(HttpServletRequest request, HttpServletResponse response, ActionMapping mapping, ServletContext context) {
// request map wrapping the http request objects
Map requestMap = new RequestMap(request);
// parameters map wrapping the http paraneters.
Map params = null;
if (mapping != null) {
params = mapping.getParams();
}
Map requestParams = new HashMap(request.getParameterMap());
if (params != null) {
params.putAll(requestParams);
} else {
params = requestParams;
}
// session map wrapping the http session
Map session = new SessionMap(request);
// application map wrapping the ServletContext
Map application = new ApplicationMap(context);
return createContextMap(requestMap, params, session, application, request, response, context);
}
由此可以猜想Get的乱码并不是webwork的问题,很可能与tomcat有关。再google了一下发现了tomcat5对get和post方法分开处理,并且request.setCharacterEncoding对get方法没有作用,这需要设置server.xml可以从根本上解决QueryString中文乱码的问题了。具体方法是对Connector元素设置URIEncoding或者useBodyEncodingForURI=true。这样代码中的那些丑陋的转编码设置就可以去掉了。

没有评论:
发表评论