I have a filter:
class MyFilters {
def filters = {
before = {
render(view: "/test")
return false
}
}
}
This works great on pages where I'm using a controller to handle the request, showing the contents of test.gsp instead of the page I requested. However, when I try to access a page that maps directly to a GSP file, I get a 404 error.
Changing the render to simply render "test"
produces the same results, as does commenting it out and just leaving the return false
.
Grails is a MVC framework. If you want to map an URL directly to a GSP (without redirection through a controller and action) you need to explain this to grails within your UrlMappings.groovy
. There you can define your "shortcuts". E.g.:
static mappings = {
"/$viewName"(view:"/index") {
constraints {
viewName([some constraints])
}
}
}
Which will render views/index.gsp
without going through a controller. If you do NOT define a controller mapping (or at least a view mapping) for those URLs, you canNOT use grails filters:
If you really want to intercept ALL requests, you can add a servlet filter to your grails application like this:
import javax.servlet.*
import org.springframework.web.context.support.WebApplicationContextUtils;
class TestFilter implements Filter {
def applicationContext
void init(FilterConfig config) throws ServletException {
applicationContext = WebApplicationContextUtils.getWebApplicationContext(config.servletContext)
}
void destroy() {
}
void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("this filter has been called");
}
}
In here you can do your redirections or renderings based on the applicationcontext
and the current request
.
You need to add this filter to your web.xml
. On how to do this, have a look at: How do i use a servlet in my grails app?