简体   繁体   中英

Grails passing object to gsp

I want to pass my database User object from controller to .gsp page so I can use it's properties in the view. Here's the controller code:

def login(String username, String password){
        def userList = getUserListFromDatabase();
        User usr = new User(username: username, password: password);
        println usr.username + '   ' + usr.password;
        username = params?.username;
        password = params?.password;
        println userList.size();
        for(User u : userList){
            println 'username: ' + u.username + ' password: ' + u.password;

            if(u.password.equals(password) && u.username==username){
                User user = u;
                flash.user = u;
                render (view: 'login.gsp');
                //debug
                println 'user.username: ' + user.username;
                return;
            }

        }
        render 'login failed';
    }

And that's how I'd like to show it in the view:

</head>
    <g:set var="now" value="${new Date()}"/>
    <g:set var="user"/>
<body>
        Login successful!<br/>
        User: ${user?.username}<br/>

</body>

What would be a proper way to pass the object with all it's properties to the view? I can't get to it.

I would really refactor your logic here. It is fetching all the user data and looping over to find the correct user. If your user table is large, your login system will slow down because it will loop over each user.

def login(String username, String password){
        // def userList = getUserListFromDatabase();
        User usr = User.findByUsernameAndPassword(params.username, params.password)
        //println usr.username + '   ' + usr.password;
        //username = params?.username;
        //password = params?.password;
        //println userList.size();
        //for(User u : userList){
            println 'username: ' + u.username + ' password: ' + u.password;

            //if(u.password.equals(password) && u.username==username){
            if(usr){
                //User user = u;
                flash.user = usr;
                render (view: 'login.gsp', model:[user:usr]);  // pass the user to view
                //debug
                println 'user.username: ' + user.username;
                return;
            }

        //}
        render 'login failed';
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM