Monday, December 8, 2008

GSP Page Without a Controller

Grails uses convention to serve up .gsp views using the name of an action in a controller.  For example, if you have a list action in a BookController Grails will try to load grails-app/views/book/list.gsp when this action is called.  But what if you want to use a .gsp but do not need or want a controller?  How can you call that page in Grails?  Like most things in Grails, there is more than one way to do this and they are all easy.

You can create the .gsp file in /grails-app/views or directly in the web-app directory.  I'd prefer the former since that's where all your other .gsp pages are going to be.  If you do either of these, then you can call the page like this:  myapp/mypage.gsp.  Or, if you nested the .gsp in a sub-directory, like this: myapp/mysubdir/mypage.gsp.  In any case you will have to include the .gsp extension and that's a bit ugly.  You can fix this with URL mapping by adding something like "/mypage"(view:"mypage") to the mappings block of your URLMapping class.  Now you can just call myapp/mypage and all is well.

With any of these approaches you have most of the power of GSP.  You can use the standard Grails GSP tags as well as any custom tags added to your project, you can include Groovy code in your pages (but please keep it to a minimum) and you have access to the objects that Grails makes available to all GSP pages, such as request, session and params.  What you don't have is a way to pass model data to your page or to perform other operations before your page is rendered.

Keep in mind that a controller action does not need to have any code in it.  So, you can always just create a controller with actions named the same as your .gsp file and then Grails will render it by convention.  If  your app includes other pages that are called from controllers then this will keep you app more consistent as well as making it easier to later add more functionality.    Maybe it's 6 of one and a half dozen of the other but at least it's nice to know that whichever way you go, Grails makes it easy.

1 comment:

Roshan Shrestha said...

I prefer not to allow users to access JSP pages. I typically put the JSP pages under WEB-INF, thus it is not accessible directly to users.

I wonder if it is possible in Grails to restrict access to GSPs while still keeping them under grails-app/views folder (i.e., not moving them under WEB-INF)?