我有一个设置 session 属性 A
和 B
的操作类。我知道值存在并且它们不是 null
。
在 Freemarker 模板中,我试图通过使用以下表达式来获取这些值
<#if session.A?exists>
${session.A}
</#if>
或
<@s.property value="%{#session.A}" />
在得到下面的错误,
<#if session.A?exists> Expression session is undefined on line 39
据我对 Freemarker Struts2 的了解,我们不需要做任何额外的设置,因为 Freemarker 的 jars 与 Struts2 捆绑在一起,我原以为 Freemarker 可以访问值堆栈,但似乎我在这里弄错了.有人可以看看我错过了什么吗?我在 S2 2.15.3
下面是附加代码,在 Action 类中,我向 session 对象添加值,
sessionMap.put("A", A);
sessionMap.put("B", B);
System.out.println("Inside loop test 2!");
String[] args = null;
SendEmail.main(args);
return "success";
现在sendEmail类包含freemarker配置,
Configuration cfg = new Configuration();
cfg.setClassForTemplateLoading(SendEmail.class, "");
Template template = cfg.getTemplate("SendEmail.ftl");
Map<String,String> rootMap = new HashMap<>();
Writer out = new StringWriter();
try {
template.process(rootMap, out);
} catch (TemplateException | IOException templateException) {
logger.error("Freemarker Template processing exception", templateException);
}
body.setContent(out.toString(), "text/html");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(body);
message.setContent(multipart, "text/html");
Transport.send(message);
session 映射声明为
private Map<String, Object> sessionMap;
最佳答案
变量名在Freemarker中区分大小写,session存储在Session
下(大写)。
所以,你的代码应该是:
<#if Session.A?exists>
${Session.A}
</#if>
或者(因为 exists
内置已弃用)
<#if Session.A??>
${Session.A}
</#if>
关于java - 无法访问 freemarker 模板中的 session 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24146142/