Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
595 views
in Technique[技术] by (71.8m points)

groovy - Dynamic Grails Url Mapping config

How can I dynamically build a list of mappings - instead of:

class UrlMappings {
static mappings = {
   "/helpdesk/user/$action?/$id?" (controller="helpdeskuser")
   "/helpdesk/group/$action?/$id?" (controller="helpdeskgroup")
   "/helpdesk/company/$action?/$id?" (controller="helpdeskcompany")
   "/helpdesk/account/$action?/$id?" (controller="helpdeskaccount")
   "/admin/company/$action?/$id?" (controller="admincompany")
   "/admin/account/$action?/$id?" (controller="adminaccount")
 }
}

something like this pseudo code:

class UrlMappings {
static mappings = {
   application.controllerClasses.each {
     if(it.name.startsWith('helpdesk'))
        "/helpdesk/${it.name}/$action?/$id?" (controller="${it.name}")
     if(it.name.startsWith('admin'))
        "/admin/${it.name}/$action?/$id?" (controller="${it.name}")
   }
 }
}

(I don't understand what the static mappings are - a hash map? free variables?)

What I am trying to achieve are mappings based on the controller type - e.g. helpdesk, admin or user controllers. Once I have set up the mappings I want to add security based on URLs but I don't want to map each controller individually:

grails.plugins.springsecurity.interceptUrlMap = [
   '/helpdesk/**':   ['ROLE_HELPDESK','ROLE_ADMIN'],
]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I've just done the following in my application:

import org.codehaus.groovy.grails.commons.ApplicationHolder

class UrlMappings {
  static mappings = {        
    for( controllerClass in ApplicationHolder.application.controllerClasses) {
      // Admin Controllers first
      if( controllerClass.name.startsWith("Admin")){
        // note... fixes the case so that AdminUserController maps to /admin/user
        "/admin/${controllerClass.name[5].toLowerCase() + controllerClass.name[6..-1]}/$action?/$id?" {
          controller = "admin${controllerClass.name[5..-1]}".toString()
        }
      }
    }
  }
}

I'd not actually done this before, your question prompted me to fix this is my app. It's been one of those things I've been trying to do for a while.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...