2016-09-10 42 views
-1

我在那裏我在成批讀了大量文件,並將其轉換成JSON將其發送到一個Spring MVC控制器代碼,我的方法看起來是這樣的,我通過我想要的開始的偏移和CHUNKSIZE在noBytes,結果被傳遞到轉化成JSON和發送到我的控制器打開組塊到網頁中的Java

public String readByteBlock(File file, int offset, int noBytes) throws IOException { 
    InputStream in = new FileInputStream(file); 
    byte[] result = new byte[noBytes]; 
    in.skip(offset); 
    in.read(result, 0, noBytes); 
    return FileSaver.byteArrayToString(result, noBytes); 
} 

我有問題,使下一個和以前的拼版作業在我的控制器

@RequestMapping("/page/{id}") 
@ResponseBody 
    File file = new File("C:/teste.txt"); 
    FileSaver fs = new FileSaver(); 
    int byteblock = 100;   
    int offset = 0; 
    if(id.equals("next")){  
     offset = (int) req.getSession().getAttribute("prevEndPos"); 
     String s = fs.readByteBlock(file, offset, byteblock);  
     req.getSession().setAttribute("prevStartPos", offset);  
     req.getSession().setAttribute("prevEndPos", (offset + byteblock));  
     return s; 
    } 
    if(id.equals("prev")){ 
     offset = (int) req.getSession().getAttribute("prevStartPos") - byteblock ; 
     if(offset < 0){ 
      String s = fs.readByteBlock(file, 0, byteblock); 
       return s; 
     } 
     String s = fs.readByteBlock(file, offset, byteblock);   
     req.getSession().setAttribute("prevStartPos", (offset - byteblock));  
     return s; 
    } 
    String s = fs.readByteBlock(file, 0, byteblock); 
    req.getSession().setAttribute("prevStartPos", offset); 
    req.getSession().setAttribute("prevEndPos", (offset + byteblock)); 
    return s; 

所以文件的每個塊將投入在米HTML表y應用程序中,我將當前塊startByte和endByte保存到我的會話中,但是當用戶按下我的頁面上的上一個按鈕時,我怎麼知道上一個塊的開始和結束位置?自會話將保持當前頁面,而不是以前的一個

回答

2

首先是一個關於分頁的小概述。 簡單分頁僅具有兩個屬性:

  1. 頁大小
  2. 頁碼

後端意願發送回數據和以下的元數據:

  1. 總頁數
  2. 當前頁碼
  3. 當前頁面大小

然後客戶端負責通過發送頁碼和頁面大小來請求它想要的數據塊,後端會計算偏移量並結束。唯一要注意的是,如果用戶增加頁面大小,然後頁面(在以前的呼叫收到客戶端)不再有效的總數,但是在這些情況下,服務器只是沒有返回數據,並新的元數據。 這種方法被許多框架所使用,如後端的Spring Data和前端的EXT JS。

既然你使用Spring,你應該只創建一個同時擁有的數據和元數據的DTO類:

Class PageResult { 
    String data; 
    int totalPageCount; 
    int currentPage; 
    int pageSize;  
} 

在您使用字符串的傳輸數據要知道,你可能需要調用前端的JSON.parse(),你的JSON將被字符串轉義,看起來很愚蠢;如果您使用Jacksons ObjectMapper讀取數據,我會建議使用返回JsonNode的ObjectMapper.readTree(),並將其放入DTO類。

在前端,你可以做一個下拉與建議的頁面大小,和頁碼輸入框。如果你想要下一個和上一個,只需發送當前頁面+/- 1和頁面大小的請求,那麼後端將計算開始,結束和總頁數。

-1

而不是添加兩個int屬性到您的會話,爲什麼不加整數的兩個數組,包含適當的值?並添加一個'頁面'屬性,所以你可以做一些像

if(id.equals("prev") { 
    List<Integer> offsetStarts = req.getSession.getAttribute("offsetStarts); 
    List<Integer> offsetEnds = req.getSession.getAttribute("offsetEnds); 
    int lastPage = req.getSession.getAttribute("page"); 
    int desiredPage = lastPage -1; 
    int offsetStart = offsetStarts.get(desiredPage); 
    int offsetEnd = offsetEnd.get(desiredPage); 
    // get the chunk as desired, and return it 
    req.getSession().setAttribute("page", desiredPage); 
} 
// if it's a new chunk, append offsets to the arrays