以项目文件utf-8编码为例
1.检查ftl文件编码,确定为utf-8无bom模式
2.不集成到srping中:
Configuration config=new Configuration(); config.setDefaultEncoding("UTF-8"); config.setServletContextForTemplateLoading(getServletContext(), "/WEB-INF/templates"); config.setTemplateUpdateDelay(0); Template t=config.getTemplate("testansi.ftl"); System.out.println(t.toString());
3.集成到spring中:
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"> <property name="templateLoaderPath" value="/WEB-INF/templates" /><!--指定模板文件目录--> <property name="freemarkerSettings"><!-- 设置FreeMarker环境属性--> <props> <prop key="template_update_delay">0</prop><!--刷新模板的周期,单位为秒--> <prop key="classic_compatible">true</prop><!-- 此属性可以防止模板解析空值时的错误 --> <prop key="defaultEncoding">utf-8</prop><!--模板的编码格式 --> </props> </property> </bean>
4.t.toString(),输出正常表示编码设置正确,前台显示若还为乱码,则需设置
res.setCharacterEncoding("utf-8");