2012-07-20 54 views
0

我想實現一種客戶端分頁,其中我只在一次顯示X記錄,然後當客戶端想要看到更多的數據時,我顯示下一個X記錄等等。爲此,我嘗試使用會話變量,但每次檢查其值時都是空的。我真的不知道那麼多關於Spring MVC所以任何幫助,將不勝感激:Spring 3 MVC會話變量存在多久?

@Controller 
@RequestMapping(value = "/api/rest/da") 
@SessionAttributes({"sessionRowKey"}) 
public class DAController { 
    /** 
    * Default constructor for DAController 
    */ 
    public DAController() { 
    } 

    /** 
    * Initialize the SessionAttribute 'sessionRowKey' if it does not exist 
    */ 
    @ModelAttribute("sessionRowKey") 
    public String createSessionRowKey() 
    { 
     return ""; 
    } 

我在這裏檢查,如果值是空的,這是我初始化它,然後將該值設置:

@RequestMapping(value = "/getModelData/{namespace}/{type}/{rowkey:[^\\.]*\\.[^\\.]*}", method = RequestMethod.GET) 
public 
@ResponseBody 
Map<String, Map<String, String>> getModelData(String namespace, 
               String type, 
               String rowkey, 
               @ModelAttribute("sessionRowKey") String sessionRowKey, 
               HttpServletRequest request) 
{ 
    try 
    { 
     ModelType modelType = ModelType.fromString(type); 
     Model model; 
     if(modelType == ModelType.STATISTICAL) //page the data 
     { 
      //code abstracted 
      List<KeyValue> records = results_arr[30].list(); 

      if(sessionRowKey.equals("")) 
      { 
       model = modelReader.readModel(namespace, modelType, rowkey); 
       request.getSession().setAttribute("sessionRowKey", records.get(0).toString()); 
      } 
      else model = modelReader.readModel(namespace, modelType, sessionRowKey); 
     } 
     else 
     { 
      model = modelReader.readModel(namespace, modelType, rowkey); 
     } 
    } 
    catch (Exception e) 
    { 
     logger.log(Level.ERROR, "Error in DAController.getModelData: " + e.getMessage()); 
    } 
} 

每次我檢查會話變量時,它總是「」,會話變量存活多久?

+0

問題不在於會話變量的使用壽命。添加一些日誌記錄以查看何時調用哪些方法。關閉袖口,我不知道是否多次調用createSessionRowKey()。 – DwB 2012-07-20 14:26:19

+0

是的,嘗試刪除createSessionRowKey()方法並檢查(sessionRowKey == null)而不是sessionRowKey.equals(「」)。 – 2012-07-20 14:32:57

+0

@DwB一個好主意,我添加了一個日誌語句,並且該方法只執行一次。 – 2012-07-20 14:33:42

回答

1

而不是@ModelAttribute註釋參數(sessionRowKey),使用HttpSession參數並使用此參數獲取sessionRowKey。例如:

... HttpSession httpSession, ... 

... 

String sessionRowKey = (String)httpSession.getAttribute("sessionRowKey"); 

... 

注意:以上是針對Java EE 5及以上版本的。對於J2EE 1.4,在使用HttpSession.getValue和HttpSession.setValue方法之前。

+0

謝謝!我會給這個鏡頭併發回,我之前沒有看到過這個方法。 – 2012-07-20 18:33:49

+0

您還需要使用httpSession.setAttribute(「sessionRowKey」,someValue)設置會話屬性。 – DwB 2012-07-20 19:19:26

+0

這結束了工作,謝謝。 – 2012-07-20 19:21:39