2014-09-23 47 views
0

Im新到grails,現在我被卡住了。在啓動時在頁面上填充字段 - Grails應用

我創建了我的應用程序,它工作正常。

現在我想填充啓動頁面上的一些字段(在我的情況下稱爲Report.gsp),在執行一些查詢以檢索值之後。

我有一個查詢在啓動時在引導程序中執行,但我不知道如何讓它們到我的gsp頁面以填充該字段。

這裏的引導代碼:

class BootStrap { 
     def dataSource 
     def grailsApplication 

     def init = { servletContext -> 
      initData() 
    } 

    def destroy = { 
    } 

    def initData(){ 
     println("***** in initDATA") 
     def sql = new Sql(dataSource) 

     def results 
     results = sql.execute("select * from customer where id = 42;") 
}} 

回答

0

Grails使用MVC設計模式。要將值傳遞給您的視圖(report.gsp),您需要檢索控制器中的數據,並將其傳遞給您的視圖。您的Bootstrap.groovy文件用於執行應用程序啓動時需要執行的操作,例如播種數據,而不是填充視圖。

如果這是您的主頁,您應該創建一個新的控制器和操作,並將您的根URL映射到該控制器操作,然後在該控制器操作中執行數據查找。

例如,創建HomeController.groovygrails-app/controllers

class HomeController { 

    def index() { 
    // Lookup your data 
    def customer = Customer.get(params.id) 

    // Pass the results to the view 
    [customer: customer] 
    } 
} 

然後,您可以映射根URL到這一行動中grails-app/conf/UrlMappings.groovy

"/"(controller: "home", action: "index") 

你的觀點應該再在grails-app/controllerName/actionName.gsp創建。在我們的例子,這將是grails-app/home/index.gsp

<ul> 
    <li>Customer ID: ${customer?.id}</li> 
    <li>Customer Name: ${customer?.name}</li> 
    <li>Customer Age: ${customer?.age}</li> 
    <!-- Whatever fields you'd like to display --> 
</ul> 

現在,當有人瀏覽到您的應用程序的根URL,HomeController的#索引操作將執行查找,並將數據傳遞到您的視圖來顯示。

+2

爲什麼要在'Customer.get(params?.id)'中使用null安全運算符?調用動作時,'params'屬性永遠不會爲空。 – 2014-09-24 01:06:45

+0

感謝您的幫助,至少它執行查詢,但爲什麼不能我使用的結果= sql.execute(「從客戶選擇名其中id = 42;」) – 2014-09-24 15:34:37

+0

@JeffScottBrown感謝您指出了這一點。 – Casey 2014-09-24 21:45:47