Best way to pass objects between controller actions in grails

前端 未结 3 1138
旧时难觅i
旧时难觅i 2020-12-21 10:02

I want a link to open up another view in my webapp to display information about the specified object. What is the best way to pass objects between controllers actions in gra

3条回答
  •  庸人自扰
    2020-12-21 10:08

    The earlier answers are incomplete. So, I am compiling them along with my inputs and making them clearer.

    You have two options:

    1. Chaining the actions:

      def action1() = {
          DomainClass domainInstance = DomainClass.findById(params.id);
          chain (action: 'action2', model: [domainInstance: domainInstance]); 
      }
      
      def action2() = {
          DomainClass domainInstance = chainModel?.domainInstance ?: DomainClass.findById(params.id);
          [domainInstance: domainInstance]; 
      }
      

      However, the successor action seems to use a fresh database session instead of reusing that of the predecessor (which may also be configurable in Grails, I don't know how though). So any lazily loaded entity may not be fully loaded in the successor action and may give LazyInitializationException (depending on your ORM configuration of course).

    2. Forwarding the request:

      def action1() = {
          DomainClass domainInstance = DomainClass.findById(params.id);
          forward (action: 'action2', model: [domainInstance: domainInstance]); 
      }
      
      def action2() = {
          DomainClass domainInstance = request?.domainInstance ?: DomainClass.findById(params.id);
          [domainInstance: domainInstance]; 
      }
      

    Unlike in the previous case, request forwarding reuses the existing session so lazy loading issues will not occur.

    As you can see, the syntax for both is almost identical. But one should prefer request forwarding as per the requirement in question due to the issue mentioned above. Another important detail is regarding the URL viewed in the address bar on/after page loading. Forwarding the requests will PRESERVE the page URL while chaining the actions will CHANGE the page URL to that of the latest action.

提交回复
热议问题