2014-01-27 53 views
0

我正在使用Grails。我想從一個名爲「User」的類的數據庫中提取信息並簡單地顯示它。數據存儲在MySql數據庫中。我可以連接到它,我的應用程序也可以連接到它。Grails - 拉取數據並顯示它?

具有業務邏輯的控制器「UserController」具有稱爲「用戶」的操作。它看起來像這樣:

​​

在我的腦海裏,應該的getUser簡單地得到用戶爲1的ID(它在數據庫中存在)。該用戶的內容應顯示在視圖中,也稱爲「用戶」。它看起來像這樣:

<!DOCTYPE html> 
<html> 
<head> 
    <meta name="layout" content="main"/> 
    <title>User info</title> 
</head> 
<body> 
    Last Name: ${User.lastName}<br/> 
    First Name: ${User.firstName}<br/> 
    E-mail: ${User.email}<br/><br/> 
</body> 
</html> 

我不斷收到它說以下內容的錯誤消息:

| Error 2014-01-27 13:04:07,089 [http-bio-8080-exec-10] ERROR 
errors.GrailsExceptionResolver - NullPointerException occurred when processing request: 
[GET] /TaskCheck/user 
Cannot get property 'lastName' on null object. Stacktrace follows: 
Message: Error processing GroovyPageView: Cannot get property 'lastName' on null object 

換句話說,它總是在認爲該「用戶」對象,應該已經拉表單數據庫始終爲空。我想不出任何我錯過的代碼。

你能告訴我我錯過了什麼嗎?我錯過了UserController中的一些代碼嗎?這應該需要五分鐘的時間才能完成,但這比我花費的時間要長得多。謝謝。

+2

您擁有MVC的C和V,M缺失。 :)看看['render'](http://grails.org/doc/latest/ref/Controllers/render.html) – dmahapatro

回答

1

正如在評論中指出的那樣,沒有模型返回到您的視圖。嘗試這樣的事情(也可以看看用戶指南)。

def user() { 
    def model = [:] 
    try { 

     model['user'] = User.get(1) 
    } 
    catch (Exception e) { 
     log.error("Something went wrong! ", e.message) 
    } 

    render view: 'user', model: model 
} 

然後在您的視圖中可以訪問你的模型是這樣的:

${user.lastName} 
0

謝謝dmahapatro &約書亞·摩爾。

使用「渲染」,使用視圖和模型將模型返回到視圖。你們倆都是對的。我的回答是:

class UserController 
{ 
static defaultAction = "user" 

... 

def user() 
{ 
    try 
    { 

     def userToDisplay = User.get(1) 
     render view: "user", model: [User:userToDisplay] 
    } 
    catch(Exception e) 
    { 
     log.error("Something went wrong! ", e.message) 
    } 
} 

} 

我一直試圖做一個return語句,就像我會用在所有其他語言。

我需要更加努力地擺脫我的.Net習慣。

+0

只需FYI BobaFett就可以做到。你只需要將它作爲一個映射返回:'return [User:userToDisplay]' – Kelly

相關問題