Grails中的跳转页面大概有以下几种方式:
1. return model
- def show = {
- def b = Book.get( params['id'] )
- return [ book : b ]
- }
没有显式返回model时,action会自动把当前controller的property当作model返回,而模版的地址则为<...>/controller/action.gsp
2. return view
- import org.springframework.web.servlet.ModelAndView
- ...
- def index = {
- def favBooks = // get some books just for the index page, perhaps your favorites
- // forward to the list view to show them
- return new ModelAndView("/book/list", [ bookList : favBooks ])
- }
3. redirect
- redirect(action:list)
当跳转到另一个controller的action时,最好使用这种方式,也可以带参数,如:
- redirect(controller:'apartment',action:'show',id:apartment.id)
4. render
- // write some markup
- render {
- for(b in books) {
- div(id:b.id, b.title)
- }
- }
- // render a specific view
- render(view:'show')
- // render a template for each item in a collection
- render(template:'book_template', collection:Book.list())
- // render some text with encoding and content type
- render(text:",contentType:"text/xml",encoding:"UTF-8")
Grails中变量的scope分类和传统的jsp大致相同,分为servletContext, session, request, flash. 比较新颖的是flash,意思是在当前request和下一个request中保持,这样一来处理消息和错误就非常方便了。
- def findBy = params["findBy"]
- def appContext = servletContext["appContext"]
- def loggedUser = session["logged_user"]
- flash['message'] = "User not found for id ${params['id']}"
因此,request的信息,grails不会像OGNL那样设置到controller中去,而要从params里面取,比如params.id 。