【问题标题】:Add URL Mapping on demand按需添加 URL 映射
【发布时间】:2017-02-27 08:07:49
【问题描述】:

我的 grails 项目至少有 20 个控制器,每个控制器至少有 4 个方法,并且还在继续增长。我决定像这样注释每个方法:

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 都放在这里,只是维护起来很乏味。

【问题讨论】:

    标签: grails url-mapping


    【解决方案1】:

    我强烈建议你用注释摆脱这个想法,而是将你的项目分成几个插件(每个 - 一个单独的 grails 应用程序)与 gradle 绑定在一起。

    一些有用的信息:

    1. https://docs.gradle.org/current/userguide/custom_plugins.html
    2. https://docs.gradle.org/current/userguide/multi_project_builds.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-18
      • 1970-01-01
      • 1970-01-01
      • 2016-07-05
      • 2012-07-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多