2017-02-27 92 views
0

我的grails項目至少有20個控制器,每個控制器至少有4個方法,並且它正在不斷髮展。我決定註釋這樣每一個方法:按需添加URL映射

import enums.URLMapped 

class HomeController { 
    @URLMapped(url="/", alias="home") 
    def landingPage() { 
     render(view: "/index") 
    } 
} 

我如何可以追加動態的URLMapping.groovy這裏面的URL值?我可以這樣做:

import enums.URLMapped 
import java.lang.reflect.Method 
import org.apache.commons.lang.StringUtils 
import org.codehaus.groovy.grails.commons.DefaultGrailsControllerClass 
import org.codehaus.groovy.grails.commons.GrailsApplication 

class UrlMappings { 
    static mappings = { 
     "/$controller/$action?/$id?(.$format)?"{ 
      constraints { 
       // apply constraints here 
      } 
     } 

     // My annotation crawler/parser 
     for(DefaultGrailsControllerClass controller in GrailsApplication.getControllerClasses()) { 
      for(Method method in controller.getClazz().getDeclaredMethods()) { 
       if(!method.isSynthetic()) { 
        if(method.isAnnotationPresent(URLMapped.class)) { 
         URLMapped url = method.getAnnotation(URLMapped.class) 
         name "${url.alias()}": "${url.url()}" { 
          action="${method.getName()}" 
          controller="${StringUtils.capitalize(controller.getClazz().getSimpleName().split(/Controller/).getAt(0)}" 
         } 
         /* What I want to achieve above is this static URL: 
          name home: "/" { 
           action="landingPage" 
           controller="Home" 
          } 
         */ 
        } 
       } 
      } 
     } 
    } 
} 

但問題是,static mapping是一個封閉,你不應該假設循環裏面(?)。那麼如何添加我的網址?我始終可以將所有鏈接的所有靜態URL都放在這裏,這只是令人乏味的維護。

回答