Search code examples
http-redirectgrailsviewcontroller

How exactly redirect page after action in the controller (grails)


So I have the logout function and i want to return to login page after logout. My controller Named LoginController.groovy. But after logout it only refresh the page and not direct it. Btw, it created by spring security plugin.

/**
 * go to login page when successful logout.
 */
def logout() {
    if(request.logout()) // Logout current user
    redirect(controller: 'Login', action: 'index') // Redirect to the login page
}


/**
 * Default action; redirects to 'defaultTargetUrl' if logged in, /login/auth otherwise.
 */
def index() {
    if (springSecurityService.isLoggedIn()) {

        redirect controller:'Login', action:'homepage'

    }
    else {
        redirect action: 'auth', params: params
    }
}


 /**
 * Show the login page.
 */
def auth() {

    def config = SpringSecurityUtils.securityConfig

    if (springSecurityService.isLoggedIn()) {
        //redirect uri: config.successHandler.defaultTargetUrl
        redirect controller:'Login', action:'homepage'
    }

    String view = 'auth'
    String postUrl = "${request.contextPath}${config.apf.filterProcessesUrl}"
    render view: view, model: [postUrl: postUrl,rememberMeParameter: config.rememberMe.parameter]


}

Solution

  • But after logout it only refresh the page and not direct it. Btw, it created by spring security plugin.

    You have this:

    def logout() {
        if(request.logout()) 
        redirect(controller: 'Login', action: 'index')
    }
    

    That is the equivalent of this:

    def logout() {
        if(request.logout()) {
            redirect(controller: 'Login', action: 'index')
        } else {
            render view: 'logout', model: [:]
        }
    }
    

    That means the redirect will only happen if .logout() returns true (or something that evaluates to Groovy truth).