W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
使用 Freemarker 作為模板引擎。
Hasor 框架內(nèi)置了 Freemarker 渲染引擎插件,您只需要引用 freemarker 的 jar 包,然后配置一下渲染引擎即可。
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
public class StartModule extends WebModule {
@Override
public void loadModule(WebApiBinder apiBinder) throws Throwable {
apiBinder.suffix("htm").bind(FreemarkerRender.class);//設(shè)置 Freemarker 渲染器
}
}
您可以通過 *.htm
的形式訪問您的請(qǐng)求處理器。然后使用 freemarker 進(jìn)行渲染。
@MappingTo("/index.htm")
public class Index {
public void execute(RenderInvoker invoker) {
...
}
}
如果您是 restful 方式,您還可以通過 @Produces 注解指定渲染器
@MappingTo("/index.htm")
public class Index {
@Produces("htm")
public void execute(RenderInvoker invoker) {
...
}
}
你也可以在處理表單設(shè)置渲染的頁(yè)面時(shí),指定渲染引擎。如下:
@MappingTo("/login.do")
public class Login {
public void execute(RenderInvoker invoker) {
if (test){
invoker.renderTo("htm","/welcome.htm");
} else {
invoker.renderTo("jsp","/error.jsp");
}
}
}
Hasor 的內(nèi)置 Freemarker 還允許使用您自定義的 Freemarker 引擎作為渲染器引擎,而不是內(nèi)置創(chuàng)建的。(使用用戶自己創(chuàng)建的 Freemarker 引擎會(huì)讓開發(fā)者更加靈活的掌控整個(gè)程序)
我們有兩種方式進(jìn)行擴(kuò)展,第一種方式繼承已有的 Freemarker 渲染器進(jìn)行擴(kuò)展。
public class MyFreemarkerRender extends FreemarkerRender {
@Override
protected Configuration newConfiguration(AppContext appContext,
ServletContext servletContext) throws IOException {
// 創(chuàng)建 Freemarker 引擎
return ...
}
@Override
protected void configSharedVariable(AppContext appContext,
ServletContext servletContext, Configuration freemarker) throws TemplateModelException {
...
super.configSharedVariable(appContext, servletContext, freemarker);
freemarker.setSharedVariable("varKey", ...); // 自定義變量
}
}
public class StartModule extends WebModule {
@Override
public void loadModule(WebApiBinder apiBinder) throws Throwable {
apiBinder.suffix("htm").bind(MyFreemarkerRender.class);//設(shè)置 Freemarker 渲染器
}
}
第二種方式,比較簡(jiǎn)單,您只需要將 Freemarker 的 Configuration 對(duì)象提供出來即可。
public class StartModule extends WebModule {
@Override
public void loadModule(WebApiBinder apiBinder) throws Throwable {
apiBinder.suffix("htm").bind(FreemarkerRender.class); //設(shè)置 Freemarker 渲染器
apiBinder.bind(Configuration.class).to( ... ); //配置渲染引擎
}
}
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: