Sumon Bappi
Sumon Bappi

Reputation: 2019

compare string with the retrieved value in grails controller

I am trying to create a login action for login. I am getting the value from database. But the problem is that when I check the value with a string it's doesn't work properly and the else part executed and shows the message in the browser. I am using grails 2.1.0. I have no idea how to do it although I assume that this is a so normal problem. Can anyone please help me on this? Here is my code below :

def loginAction = {
    def username = params?.username
    def password = params?.password
    def user = Login.findAllByUsernameAndPassword(username, password)
    def status = user.status
    def role = user.role
    println(">>>>>>>>>>>>>>>>>>>>>>>> "+role);

    if(role == 'admin'){
        render "Admin Login"
    }else if(role == "teacher"){
        render "Teacher's Login"
    }else if(role == "student"){
        render "student login"
    }else{
        flash.message = message(code: "Log-In failed, Please try again !!!")
        redirect(controller:"login",action:"login")
    }
}

Note that, the println works and give the output below :

>>>>>>>>>>>>>>>>>>>>>>>> [admin]

Upvotes: 0

Views: 294

Answers (1)

Igor Artamonov
Igor Artamonov

Reputation: 35961

You are using .findAllBy, so you have a list of users, with one element in this list. As a result, role variable have [admin] value (see provided output), it's a list of roles. List of strings, not a string.

You're comparing this list with admin as a string value. So, that's right ["admin"] != "admin"

Just use findBy instead, like:

def user = Login.findByUsernameAndPassword(username, password)

Upvotes: 1

Related Questions