天天看点

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

在java web工程中加入html文件,出现中文乱码问题。html的编码方式为UTF-8。一直找不到原因,后来创建了一个jsp文件,将html文件内容复制到jsp文件里面就能正常显示。做了一些测试,发现把sitemesh装饰器去掉后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,只要没排除装饰还是不行。