用Freemarker生成静态页后,访问时老是出现乱码.
关于生成静态页的过程用的都是UTF-8编码.也没出现什么问题,生成的静态页双击打开,都很正常,没有出现乱码问题.
但是项目(用到struts2.0)布署到TOMCAT中,老是出现乱码问题,浏览器打开生成的静态页时,老是用ISO-8859-1的编码打开,必然是乱码,右击》编码》UTF-8打开,一切显示正常,所以应该是项目中filter的编码有问题.
当把WEB.XML中的Fileter去了,就没有乱码问题.
<filter>
<filter-name>struts</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
所以应该在该Filter里配置编码.查看 org.apache.struts2.dispatcher.FilterDispatcher 的init方法中没有encoding参数.所以就自己创建个Filter,如下
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.apache.struts2.dispatcher.FilterDispatcher;
public class NewFilterDispatcher extends FilterDispatcher {
private static String encoding = "UTF-8";
public void init(FilterConfig filterConfig) throws ServletException {
super.init(filterConfig);
String encodingParam = filterConfig.getInitParameter("encoding"); //获取web.xml下的初始化参数
if (encodingParam != null && encodingParam.trim().length() != 0) {
encoding = encodingParam;
}
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding(encoding); //设置request编码格式
response.setCharacterEncoding(encoding);//设置response编码格式
super.doFilter(request, response, chain);
}
}
再在web.xml中进行配置
<filter>
<filter-name>struts</filter-name>
<filter-class>
com.filter.NewFilterDispatcher
</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>struts</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
问题解决.