使用你喜歡的模版引擎渲染頁面

    目前 Web 網站的開發 基本都用到了模版引擎,使用 Hasor 開發 web 能夠使用你喜歡的任何模版解析引擎。在開始本文以前,先推薦您三篇相關文章:html

    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 請求並獲取請求參數》java

用模版渲染頁面

    Hasor 的頁面渲染引擎和請求資源的擴展名有必定的關聯性,咱們以一個例子來講明。首先咱們有一個頁面 「index.html」這個頁面打算使用 Freemarker 來進行渲染。web

    那麼咱們第一步須要編寫一個渲染器,並將這個渲染器和 「html」類型資源請求綁定到一塊兒。json

@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」 結尾的請求都會走這個渲染器。api

    接下來咱們作 Freemarker 和 Hasor 的整合:app

@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 中,下面是註冊渲染器的一種方式。ide

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;
    }
}
相關文章
相關標籤/搜索