![](/img/trans.png)
[英]How to add a self-defined MouseMotionListener to a JPanel?
[英]how to access data in freemarker template with self-defined directive?
我要求我要與freemaker一起實現,我已經知道freemarker是如何工作的,就像這樣
template.process(dataMap,out);
dataMap包含我們用來填充模板的數據,當然所有數據都實現了TamplateModel接口,如果我們使用用戶定義的指令沒有區別,因為用戶定義的指令實現了TemplateDirectiveModel,這個接口實現了TemplateModel,我需要什么要做的是訪問存儲在會話中的數據,然后在我的指令中使用這些數據。像這個<@authCheck> </@authCheck>
,我的auth數據存儲在會話中,所以我需要從我的會話中獲取這些數據指示。
ps:我使用springMVC和freemarker
模板的運行時環境由Environment
對象表示,您也可以將其作為TemplateDirectiveModel
-s的參數獲取,或者可以使用靜態方法Environment.getCurrentEnvironment()
從TLS獲取。 您可以使用setCustomAttribute(String name, Object value)
將其他對象(如會話)附加到Environment,因此您的指令可以使用env.getCustomAttribute(name)
來獲取它。
每個Template.process
調用都在內部創建自己的Environment
對象。 要在調用主模板之前訪問它,您必須執行此操作而不是簡單地調用Tempalte.process
:
Environment env = myTemplate.createProcessingEnvironment(root, out);
env.setCustoomAttribute("session", sesssion);
// You can addjust other environment settings here too.
env.process(); // template is called here to render the output
另一種可能性是將會話置於數據模型中。 TemplateDirective
-s可以通過env.getDataModel()
訪問數據模型。
注意:我的答案沒有直接回答這個問題。
正如你所提到的,你使用Freemarker和Spring-MVC,我猜你也使用Spring-Security,如果沒有,建議你這樣做。
這是我在Freemarker模板中使用Spring-Security taglib的方法。
<#macro auth expr>
<#assign security=JspTaglibs["http://www.springframework.org/security/tags"] />
<@security.authorize access=expr>
<#nested>
</@security.authorize>
</#macro>
以上宏可以像:
<#import "/mywebsitename/foomacro.ftl" as foo>
<@foo.auth "isAnonymous()">
<a href="/signup">Signup</a>
</@foo.auth>
<@foo.auth "hasRole('ROLE_USER')">
<a href="/profile">Profile</a>
</@foo.auth>
我也很樂意知道我的方法的弱點,例如我們可以通過使用其他方法獲得更好的性能嗎?
例如,這個虛構的代碼可能表現更好嗎?
<@foo.authCheck AUTH_OBJ_IN_SESSION "ROLE_USER">
<a href = '/profile'>Profile</a>
</@foo.authCheck>
<#macro authCheck authObj role>
<#if authObj.hasRole(role)>
<#nested>
</#if>
</#macro>
我自己的猜測是,它們沒有太大區別,因為它們都使用來自用戶會話的身份驗證對象。 那么為什么不使用Spring-Security的測試(即用型)taglib?
ps我通常在模板中訪問SESSION變量,就像模型或請求變量一樣,例如${VAR_IN_SESSION}
。 也許那是因為我在我的春季配置中設置了<property name="exposeSpringMacroHelpers" value="true"/>
。 我還有<property name="exposeSessionAttributes" value="false"/>
,它似乎對不提供會話變量沒有影響!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.