目前 Web 网站的开发 基本都用到了模版引擎,使用 Hasor 开发 web 可以使用你喜欢的任何模版解析引擎。在开始本文之前,先推荐您三篇相关文章:
https://my.oschina.net/u/1166271/blog/753001《用 Hasor 谈一谈MVC设计模式》
https://my.oschina.net/u/1166271/blog/550176《Web项目,工程目录应该怎样规划?》
https://my.oschina.net/u/1166271/blog/753718《接受 Request 请求并获取请求参数》
用模版渲染页面
Hasor 的页面渲染引擎和请求资源的扩展名有一定的关联性,我们以一个例子来说明。首先我们有一个页面 “index.html”这个页面打算使用 Freemarker 来进行渲染。
那么我们第一步需要编写一个渲染器,并将这个渲染器和 “html”类型资源请求绑定到一起。
@Render("html")
public class FreemarkerRender implements RenderEngine {
public void initEngine(WebAppContext appContext) throws Throwable {
...
}
public void process(RenderData renderData, Writer writer) throws Throwable {
...
}
public boolean exist(String template) throws IOException {
...
}
}
不光如此,您还可以同时将同一个渲染器绑定到不同类型的资源上。例如:
@Render({"html", "htm"})
这样一来,凡是 “htm” 或 “html” 结尾的请求都会走这个渲染器。
接下来我们做 Freemarker 和 Hasor 的整合:
@Render({"html", "htm"})
public class FreemarkerRender implements RenderEngine {
protected Configuration configuration;
public void initEngine(WebAppContext appContext) throws Throwable {
String realPath = appContext.getEnvironment().getServletContext().getRealPath("/");
TemplateLoader templateLoader = new FileTemplateLoader(new File(realPath), true);
this.configuration = new Configuration(Configuration.VERSION_2_3_22);
this.configuration.setTemplateLoader(templateLoader);
this.configuration.setDefaultEncoding("utf-8");//默认页面编码UTF-8
this.configuration.setOutputEncoding("utf-8");//输出编码格式UTF-8
this.configuration.setLocalizedLookup(false);//是否开启国际化false
this.configuration.setClassicCompatible(true);//null值测处理配置
//
// - 各种工具
this.configuration.setSharedVariable("escapeHtml", new StringEscapeUtils());//HTML 转译,防止XSS使用。
this.configuration.setSharedVariable("stringUtils", new StringUtils());
//
// - 环境变量
this.configuration.setSharedVariable("ctx_path", appContext.getServletContext().getContextPath());
}
public void process(RenderData renderData, Writer writer) throws Throwable {
Template temp = this.configuration.getTemplate(renderData.renderTo());
//
HashMap<String, Object> data = new HashMap<String, Object>();
for (String key : renderData.keySet()) {
data.put(key, renderData.get(key));
}
//
temp.process(data, writer);
}
public boolean exist(String template) throws IOException {
return this.configuration.getTemplateLoader().findTemplateSource(template) != null;
}
}
在最后我们需要在应用启动的时候将这个渲染器注册到 Hasor 中,下面是注册渲染器的一种方式。
public class StartModule extends WebModule {
public void loadModule(WebApiBinder apiBinder) throws Throwable {
apiBinder.bindType(RenderEngine.class).uniqueName().toInstance(new FreemarkerRender());
}
}
可以同时使用多个渲染器吗?
答案是可以的。
前面我们已经知道渲染器是需要和资源类型绑定到一起的,因此多个渲染器同时工作也不是什么难事。
没有指定“*.do”的渲染器,我可以使用已存在的渲染器渲染它么?
答案是可以的,我们看一个例子:
@MappingTo("/scene/login.do")
public class Login4Scene {
public void execute(@Valid("login") @Params LoginForm4Scene loginForm, RenderData data) {
if (data.isValid()) {
data.renderTo("htm", "/userInfo.htm");
} else {
data.put("loginForm", loginForm);
data.renderTo("htm", "/scene.htm");//使用 htm 引擎渲染页面。
}
}
}
在上面例子代码中:renderTo 方法的第一个参数指定了当前请求结果在渲染页面是通过 htm 的渲染器进行渲染。
JSON渲染器
json 渲染器是 Hasor 内置的一个渲染器,使用起来比较简单方便。我们看一个例子:
@MappingTo("/getUserInfo.json")
public class GetUserInfo {
public UserInfo execute(RenderData data) {
return new UserInfo();
}
}
当用户请求 “/getUserInfo.json” 的时候,首先会调用这个类的方法。方法返回了一个 UserInfo 对象。接着我们会把执行返回值保存到 RenderData 的 RESULT_DATA 数据中。然后在 JSON 渲染器中渲染这个数据。下面是整个 JSON 渲染器的源代码:
public class JsonRenderEngine implements RenderEngine {
@Override
public void initEngine(WebAppContext appContext) throws IOException {
}
@Override
public void process(RenderData data, Writer writer) throws Throwable {
String json = JSON.DEFAULT.toJSON(data.get(RenderData.RETURN_DATA_KEY));
writer.write(json);
}
@Override
public boolean exist(String template) throws IOException {
return true;
}
}