【问题标题】:Grails - Pull data and display it?Grails - 提取数据并显示它?
【发布时间】:2014-01-27 18:48:51
【问题描述】:

我正在使用 Grails。我想从名为“User”的类的数据库中提取信息并简单地显示它。数据存储在 MySql 数据库中。我可以连接到它,我的应用程序也可以。

具有业务逻辑的控制器“UserController”有一个名为“User”的操作。它看起来像这样:

import gorm.*


class UserController {
    static scaffold = true
    static defaultAction = "user"


    def index() {
       ...
    }

    def user() {
        try {

            def userToDisplay = User.get(1)
            return userToDisplay
        }
        catch (Exception e) {
            log.error("Something went wrong! ", e.message)
        }
    }
}

在我看来,GetUser 应该简单地获取 ID 为 1 的用户(它确实存在于数据库中)。该用户的内容应显示在视图中,也称为“用户”。它看起来像这样:

<!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 中的一些代码吗?这本应该花五分钟的时间来完成,但我花了比这更长的时间。谢谢。

【问题讨论】:

  • 你有 MVC 的 C 和 V,缺少 M。 :) 看看render

标签: mysql grails


【解决方案1】:

正如 cmets 中所指出的,您没有将模型返回到您的视图中。尝试这样的事情(并查看用户指南)。

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}

【讨论】:

    【解决方案2】:

    谢谢你,dmahapatro 和 Joshua Moore。

    使用“渲染”将模型返回到视图,其中包含视图和模型。你们俩都是对的。我的回答是:

    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 习惯。

    【讨论】:

    • 仅供参考 BobaFett 你可以做到这一点。您只需将其作为地图返回:return [User:userToDisplay]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-12
    • 2023-01-22
    • 2019-01-12
    • 1970-01-01
    • 2019-11-17
    相关资源
    最近更新 更多