原创

JavaWeb-freeMarker读取模板-非精确匹配-就近匹配


国际话多语言场景,freeMarker导出模板

boolean isEnglish = LanguageUtil.isEnglish();
String tpl = (isEnglish ? "trainEffectEvaluation_en.ftl" : "trainEffectEvaluation.ftl");

log.info("国际化:isEnglish:{},tpl:{}",isEnglish,tpl);

response.setCharacterEncoding("UTF-8");
response.setContentType("application/msword");
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
Template template = freeMarkerConfigurer.getConfiguration().getTemplate(tpl);

//2024-01-03 18:47:32.229 [XNIO-1 task-1] ERROR cn.jiangjiesheng.edu.utils.language.LanguageUtil.getLanguageCtxByRealTimeParam:225 - [13979015717894784][0] 国际化:不支持的Accept-Language:zh-CN,zh;q=0.9
//2024-01-03 18:47:32.231 [XNIO-1 task-1] INFO cn.jiangjiesheng.edu.service.train.EduTrainEffectEvaluationService.exportEvaluation:235 - [13979015717894784][0] 国际化:isEnglish:false,tpl:trainEffectEvaluation.ftl

实际加载的是 trainEffectEvaluation_en.ftl 模板,期望读取trainEffectEvaluation.ftl

准备打印模板名称时,看到注释,竟然不是精确匹配,采取 从前往后 近似匹配的。
// template.getSourceName()
/**
* The name that was actually used to load this template from the {@link TemplateLoader} (or from other custom
* storage mechanism). This is what should be shown in error messages as the error location. This is usually the
* same as {@link #getName()}, except when localized lookup, template acquisition ({@code *} step in the name), or
* other {@link TemplateLookupStrategy} transforms the requested name ({@link #getName()}) to a different final
* {@link TemplateLoader}-level name. For example, when you get a template with name {@code "foo.ftl"} then because
* of localized lookup, it's possible that something like {@code "foo_en.ftl"} will be loaded behind the scenes.
* While the template name will be still the same as the requested template name ({@code "foo.ftl"}), errors should
* point to {@code "foo_de.ftl"}. Note that relative paths are always resolved relatively to the {@code name}, not
* to the {@code sourceName}.
*
* @since 2.3.22
*/
public String getSourceName() {
return sourceName != null ? sourceName : getName();
}

//方案改模板名称,en_换到前面来。
String tpl = (isEnglish ? "en_trainEffectEvaluation.ftl" : "trainEffectEvaluation.ftl");

正文到此结束
本文目录