Grails: How can I change default view location?

2019-05-11 13:43发布

问题:

I've got controller AdminTagController. By default view will be located in /adminTag folder. Is it possible to change default folder for this controller to /admin/view? I can specify view for each method but it's not cool

Thank you

回答1:

It's possible to change it with the afterInterceptor of your controller. Check the example:

def afterInterceptor = { model, modelAndView ->
    println "Current view is ${modelAndView.viewName}"
    if (model.someVar) {
        modelAndView.viewName = "/mycontroller/someotherview"
    }
    println "View is now ${modelAndView.viewName}"
}

This is applied to all actions of your controller.



回答2:

In your case, I would do the heavy work in the controller, as only one class is impacted.

However, here is another way, using a custom GroovyPageResourceLoader.

That approach is typically used when your views are in a folder structure that doesn't follow Grails conventions. In your case, that would be overkill in my opinion.

However, here's the general idea:

1. Create a class that extends the default groovyPageResourceLoader.

Below is a very raw example.

class AdminGroovyPageResourceLoader extends GroovyPageResourceLoader {

 @Override Resource getResource(java.lang.String location) {
        if (location.contains ("/admin")) {
            return new FileSystemResource("PATH_TO_GSP_LOCATION_WITHOUT_FILE_EXTENSION")
        }

        return super.getResource(location)
 }
}

2. Override the default groovyPageResourceLoader bean

In resources.groovy or your plugin descriptor, override the groovyPageResourceLoader bean with your custom class.

A shorter path, might be some metaclass kung fu, if you don't want to override the default Spring Bean.