我的grails项目至少有20个 Controller ,每种 Controller 至少有4种方法,并且还在不断发展。我决定注释每个这样的方法:
import enums.URLMapped
class HomeController {
@URLMapped(url="/", alias="home")
def landingPage() {
render(view: "/index")
}
}
如何动态地将此URL值附加到
URLMapping.groovy
中?我可以做类似的事情: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?我总是可以在这里将所有链接的所有静态URL放在这里,维护起来很繁琐。
最佳答案
我强烈建议您摆脱带有注释的想法,而是将您的项目分成几个与gradle bundle 在一起的插件(每个插件-一个单独的grails-app)。
一些有用的信息:
关于grails - 按需添加URL映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42480608/