2014-01-12 53 views
0

我正在嘗試爲使用FreeMarker的JSF Web項目創建源代碼生成器。該項目仍處於起步階段,源代碼可在https://github.com/TarekSaid/awesome/tree/master/Awesome處獲得。在這個問題的最後,我也包含了一些UML圖。如何使用FreeMarker以編程方式創建JSF視圖?

生成器解析一個json字符串以創建不同的組件(pom.xml,web.xml,controllers和views)。

到目前爲止,我已經能夠產生兩種類型的JSF項目:

顯示的Hello,World
  • 一個簡單的JSF項目!
  • a「Hello,[NAME]」JSF項目的表單接收名稱並將其重定向到另一個視圖。

但我有意見問題。雖然當前的實現非常靈活(在ViewContent上使用某種裝飾模式)並且可行,但json字符串必須包含整個頁面。對於簡單的頁面,例如我生成的頁面,沒關係。但是,隨着我試圖產生的項目變得越來越複雜,觀點也越來越複雜。

舉例來說,這是JSON字符串我有一個簡單的「Hello World」應用程序:

{ 
    "name":"simplehello", 
    "pomFile": {"groupId":"br.com.revo", "artifactId":"simplehello", "description":"the simplest JSF Project", "javaVersion":"1.7"}, 
    "beans":[ 
    {"name":"Hello", "scope":"VIEW", "fields":[{"type":"String", "name":"hello", "value":"\"Hello World!\""}]} 
    ], 
    "views":[ 
    {"name":"hello", "welcomeFile":true, "content": 
     {"name":"html","properties":{"xmlns":"http://www.w3.org/1999/xhtml","xmlns:h":"http://java.sun.com/jsf/html"}, 
     "contents":[ 
     {"name":"h:head","contents":[{"name":"title","value":"Simple Hello"}]}, 
     {"name":"h:body", "value":"#{helloBean.hello}"} 
     ]} 
    } 
    ] 
} 

所以我能做些什麼來使用我的JSON字符串的自定義DSL並讓發電機處理視圖創作?我一直在使用Google周圍,這是我見過的可能性:

  1. 使用的FreeMarker的<#include>插入我需要的JSF組件:

    <#if content.text> 
        <#include text.ftl> 
    <#elseif content.form> 
        <#include form.ftl> 
    // etc... 
    </#if> 
    
  2. 生成一個bean是編程設計的網頁。

    看到Programmatic usage of Facelets

我怎樣纔能有效地使用FreeMarker的創建視圖?

這裏的用例,爲我的項目類別和活動圖:

Use Case Diagram Class Diagram Activity Diagram

回答

1

我解決它通過重構的ViewFile使用的,而不是它的內容來進行操作(ViewAction這一)名單。因爲到目前爲止我想要生成的項目都有標準操作(顯示消息,賦值給變量,重定向到頁面等),ViewAction具有ActionType和String的枚舉,值:

ViewAction這一

public class ViewAction { 
    private ActionType actionType; 
    private String value; 

    // getters and setters 
} 

操作類型

public enum ActionType { 
    DISPLAY, 
    ASSIGN, 
    BUTTON, 
    LINK, 
    CRUD 
} 

現在我可以根據ActionType使用FreeMarker的< #include>指令。這是不太靈活,但現在解析器不需要知道如何編碼JSF視圖,

此外,它允許更簡化我的代碼。我可以定義一個(或一系列)Model類,JSFServiceFactory相應地創建服務,而不是分離bean,視圖和模型。現在,HelloWorld應用的json更簡單:

{ 
    "name":"simplehello", 
    "pomFile": {"groupId":"br.com.revo", "artifactId":"simplehello", "description":"the simplest JSF Project", "javaVersion":"1.7"}, 
    "models":[ 
    {"name":"Hello", 
    "scope":"VIEW", 
    "title":"Simple Hello", 
    "mainPage":true, 
    "fields":[{"type":"String", "name":"hello", "value":"\"Hello World!\""}], 
    "actions":[{"actionType":"DISPLAY", "value":"#{helloBean.hello}"}] 
    } 
    ] 
}