2016-10-20 23 views
1

我有一個可以排序,搜索和過濾的列表視圖。從該列表視圖中,用戶可以通過多個步驟編輯項目。最後,在編輯和檢查更改後,用戶返回列表。現在我想讓列表使用用戶之前設置的相同的排序,搜索詞和過濾器,並顯示正確的結果。如何存儲以後再次使用的動作參數

顯示列表操作時,多個參數(排序,搜索,過濾)如何存儲和重用?

可能不理想的方式,我認爲的:通過所有需要的參數

  • 通。如果在兩個列表動作調用之間涉及多個操作,則幾乎不工作
  • 保存會話對象中的參數。這似乎需要大量的代碼來處理多個參數(檢查參數傳遞給動作,儲存新的值,如果參數沒有被通過,從會話中獲取舊的參數,處理空字符串參數):

    Long longParameter 
    if(params.containsKey('longParameter')) { 
        longParameter = params.getLong('longParameter') 
        session.setAttribute('longParameter', longParameter) 
    } else { 
        longParameter = session.getAttribute('longParameter') as Long 
        params['longParameter'] = longParameter 
    } 
    

回答

3

如果你想讓它更通用的,你可以使用一個Interceptor代替。

這或許可以概括如下:

class SessionParamInterceptor { 
    SessionParamInterceptor() { 
     matchAll() // You could match only controllers that are relevant. 
    } 

    static final List<String> sessionParams = ['myParam','otherParam','coolParam'] 

    boolean before() { 
     sessionParams.each { 
      // If the request contains param, then set it in session 
      if (params.containsKey(it)) { 
       session[it] = params[it] 
      } else { 
       // Else, get the value from session (it will be null, if not present) 
       params[it] = session[it] 
      } 
     } 

     true 
    } 
} 

靜態sessionParams持有你想存儲/從session中獲取的參數。

如果params包含列表中的元素,則它將以相同名稱存儲在session中。如果不是,則取自session(假設它存在)。

在您的控制器中,您現在可以像以前一樣訪問params.getLong('theParam')。您也可以使用Grails參數轉換:

def myAction(Long theParam) { 

} 

保存了大量的LOC。

+0

我已經運行的代碼,它似乎工作,但我沒有測試的情況下,以證明它:-) – sbglasius

+0

如果您使用Grails <3,可以在Grails過濾器中使用相同的概念 – sbglasius

1

使用session是你最好的選擇。首選時只保存偏好。我的意思是,當用戶排序或過濾時,只需在返回頁面之前將該信息保存在session,即特定<controller>.<action>中。下一次,請檢查session,如果它與<controller>.<action>有任何關係,則應用這些;否則呈現默認頁面。

爲此,您可能會使用一些Interceptor,如sbglasius, here所示。

我希望你明白我的觀點。

+0

我編輯我的問題添加一個代碼示例。這看起來像只是一個參數很多的代碼,我經常有很多哦,他們 – deflomu

1

我也使用會話。這裏是你可以適應您的需求的樣本:

def list() { 
    if (request.method == 'GET' && !request.queryString) { 
    if (session[controllerName]) { 
     // Recall params from memory 
     params.putAll(session[controllerName]) 
    } 
    } else { 
    // Save params to memory and redirect to get clean URL 
    session[controllerName] = extractParams(params) 
    redirect(action: actionName) 
    return 
    } 

    // Do your actions here... 
} 

def extractParams(params) { 
    def ret = [:] 
    params.each { entry -> 
    if (entry.key.startsWith("filter_") || entry.key == "max" || entry.key == "offset" || entry.key == "sort" || entry.key == "order") { 
     ret[entry.key] = entry.value 
    } 
    } 
    return ret 
} 
相關問題