日期:2014-05-17  浏览次数:20569 次

sitemesh装饰后的html中文乱码解决方法

应用了sitemesh装饰模板后,所有html页面,只有有中文都会出现乱码问题,导致页面加载超级慢,或直接就报错了。

郁 闷了很久,开始不知道是sitemesh搞的鬼,测试了n多都不知道是什么原因,后来搜索html乱码才知道是sitemesh引起的。

于 是搜索相关资料,综合了几个设置终于解决了,分享下解决方法。

有几个地方要改的:

1.排除不装饰的html文件目录

<!-- 在excludes元素下指定的页面将不会由SiteMesh来装饰 -->
<excludes>
?? <pattern>/index.jsp</pattern>
?? <pattern>/coos/*.*</pattern>
?? <pattern>/scripts/*.*</pattern>
</excludes>

2. 在web.xml里面加入一个filter

(1)到你apache-tomcat-6.0.14\webapps\examples \WEB-INF\classes\filters下找到SetCharacterEncodingFilter.java这个文件。
(2)把 SetCharacterEncodingFilter.java放到你的工程代码中。
(3)设置web.xml
??? <filter>
???? <filter-name>Set Character Encoding </filter-name>
???? <filter-class>你的包.SetCharacterEncodingFilter </filter-class>
???? <init-param>
?????? <param-name>encoding </param-name>
?????? <param-value>UTF-8 </param-value>
???? </init-param>
???? <init-param>
?????? <param-name>ignore </param-name>
?????? <param-value>true </param-value>
???? </init-param>
?? </filter>
?? <filter-mapping>
???? <filter-name>Set Character Encoding </filter-name>
???? <servlet-name>action </servlet-name>
?? </filter-mapping>

3.在 struts.properties 添加:
struts.locale=zh_CN
struts.i18n.encoding=UTF-8

4.在web.xml中EncodingFilter的位置应该在Struts2的FilterDispatcher之前,因为要先调 整字符集,然后进入Action。按照Struts2的API,filter的顺序是
struts-cleanup filter
SiteMesh filter
FilterDispatcher

总之,所有涉及到编码的地方都改成UTF-8吧

jsp 的 可以根据<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>来识别编码,HTML的却不行,而且没有好的解决方案。

附网上不完美的解决方案:

静态html在sitemesh中乱码的解决方法。
前提条件:sitemesh的decorator的编码全部用UTF- 8,使用SetCharacterEncodingFilter把request的encoding也
设置成UTF-8

问题 1、decorator中的内容出现乱码。
原因:
解决方法:改进SetCharacterEncodingFilter,使它对 response也设置encoding为UTF-8

问题2、被修饰的html内容出现乱码。
原因:sitemesh根据 html的contenttype(例如:text/html;charset=utf-8)来决定html文件的encoding,
如果 contenttype是像(text/html)这样的形式,sitemesh就无法知道html的encoding,这时sitemesh就
使 用DEFAULT_ENCODING即System.getProperty("file.encoding"),在jetty中正是后面那样,估计 tomcat也是这样。

解决方法:使html的encoding和 System.getProperty("file.encoding")相同。
??? 1、启动jetty时将java系统变量file.encoding设置为UTF-8,html的编码也用UTF-8.(推荐)

注:即 使是编码都是UTF-8,只要没排除装饰还是不行。