Jack_Russell
Jack_Russell

Reputation: 343

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.

Upvotes: 2

Views: 509

Answers (1)

elixir
elixir

Reputation: 1442

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';
    }

Upvotes: 2

Related Questions