grails为开发者提供了一个controller列表的默认主页,在开发时用起来确实很方便,但总不能把它用到产品环境下吧。可是在grails- app/views下面怎么找不到这个文件,也没有哪个controller和主页相关?实际上这个默认的主页独立放在web-app下,文件名是 index.gsp。把它修改为:
- <html>
- <head>
- <title>Welcome to Grails</title>
- <meta name="layout" content="main" />
- </head>
- <body>
- Hello World!
- </body>
- </html>
刷新后主页变成了Hello World!
好了,本文结束,接下来的工作就是你的了。慢着,如果不想重新编写一个主页,而是想把它重定向到一个controller怎么办?
Grails 是建立在Java的基础之上的,在Grails项目中我们可以很方便的使用Java的各种技术,包括JSP。现在把index.gsp重新命名为 index.jsp,内容改为<% response.sendRedirect("yourController/yourAction"); %>,刷新后主页就重定向到了你定义的路径。
事实上GSP是JSP的扩展,这意味着你同样可以在GSP中使用session、 servletContext,、request和response对象。把index.jsp重新改回index.gsp,内容改 为${response.sendRedirect("yourController/yourAction")}同样可以达到重定向效果。
还可以自定义一个Tag来实现重定向:
- def redirectPage={attrs->
- def url=attrs.get('url')
- response.sendRedirect("${request.contextPath}"+url)
- }
最后介绍最简单的解决方法:
打开grails-app/conf/UrlMappings.groovy,这是Grails中URL映射的配置文件,相当于Rails中的routes.rb,把它作如下修改即可:
- class UrlMappings {
- static mappings = {
- "/"(controller:"yourController",action:"yourAction")
- "/$controller/$action?/$id?"{
- constraints {
- // apply constraints here
- }
- }
- }
- }


