现在的位置: 首页 > 综合 > 正文

Spring MVC与Veclocity结合中文问题及常用中文问题总结

2013年05月26日 ⁄ 综合 ⁄ 共 2761字 ⁄ 字号 评论关闭

文章出自:http://xiecc.itpub.net/post/1476/34635

昨天在整合Spring MVC和Velocity,Sitemesh时,又碰到了久违的中文问题。唉,JSP, mysql, struts,每次都会碰到这样的问题,总是以为这种以后不会碰到这种看似初级的问题了,结果还是躲不过。网上没查到相关资料,于是开始动手跟踪Spring和Velocity的源码,弄了一天终于搞定。后来一个同学告诉我这个问题在Spring中文论坛里有精华贴,跟我最后的解决方案一样的,气死我也。不过跟踪Spring的源代码收获还是不错的,现在又对Spring的MVC framework有了更深的认识。这里把以前碰到的中文问题大概列一下,方便以后参考。

1、JSP页面显示的中文问题
这是最初级的东西,网上到处都有,不过还是列一下吧:
Page的第一行改成:<%@ page contentType="text/html; charset=gb2312" %>
Head里加:<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
2、页面Form 内容提交的中文问题
在web.xml里加入:
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<display-name>Character Encoding Filter</display-name>
<description>no description</description>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>GB2312</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>

<!-- Encoding Filter Mapping Start-->
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
呵呵,这是个简单得要命的filter,如果不用Spring的话,完全可以自己写一个。其实任何的interceptor机制都可以处理这个的,不管用Webwork还是Spring的interceptor,甚至用AOP,只要在取参数前加那么一句:request.setCharacterEncoding("GB2312");就行了。以前我用struts就是在它的RequestProcessor的populate之前加了这么一行。
3、request 的parameter里要传中文参数的问题
这个问题跟Web Container有关系,记得以前我同学用WebLogic时好象没出现这样的问题。(我一般不传中文参数,呵呵)。
Tomcat里的解决方案是在server.xml里Connector port="8080"的attribute里加URIEncoding="GB2312"
当然还有最土的解决方案,虽然不太会用到,不过还是列出来,以备最无奈的时候使用:
String encodeStr=new String(fieldValue.getBytes("8859_1"), "gb2312");
4、mysql的中文问题
首先要修改mysql配置文件的encoding为GB2312,这部分的操作不记得了,毕竟好久没用mysql了。不过据说新版的mysql里有wizard可以设的。然后把jdbc connection改成如下:
jdbc:mysql://localhost:3306/bsfbookstore?useUnicode=true;characterEncoding=GB2312
另外在写程序成尽量用PrepareStatement,少用Statement,好象jdbc驱动在解析statement里的SQL包含中文时会有问题。(用PrepareStatement也是好习惯, hibernate里全用PrepareStatement的,哈哈)
5、Spring与Veclocity结合的中文问题
第一步:
在"velocityConfig"里配置velocity.propeties文件,加下面一行:
<property name="configLocation"><value>/WEB-INF/velocity.properties</value></property>
呵呵,也可以在config里直接用Map把参数写进去,这样就不用properties文件,这个Spring的文档里都有。
然后在velocity.properties里写:
input.encoding=GB2312
output.encoding=GB2312
default.contentType=text/html; charset=GB2312(ms这一行没有用处,Spring有个地方读进这个参数,不过后来又覆盖掉了)
第二步:
接下来就是我昨天调了半天的那个地方,最后的解决方案很简单,在viewResolver配置里加一行:
<property name="contentType"><value>text/html; charset=GB2312</value></property>
呵呵,就这么一行害我debug了好久,跟踪了Velocity的Context设置,甚至改了Spring的源码,用了Filter,Spring的Handler interceptor来设置reponse的contentType就是没效果,结果发现Spring在Velocity View的render里加了这么一行:
response.setContentType(getContentType());
呵呵,原先设好的contentType都被冲掉了,因为render的时机是在postHandler之后,呵呵。
这个参数对jsp是没有用的,因为jsp会根据自己页面的contentType设定的,所以每个JSP必须设置自己的contentType,Velocity就不用啦。难怪以前用JSP的时候没碰到这个问题。

 

抱歉!评论已关闭.