2015-09-04 53 views
0

在我的一個操作中,我將Long(不是原始類型)綁定到請求參數。Spring MVC RequestParam長類型綁定總是爲空

@RequestMapping("/history") 
    public ModelAndView historyList_GET(
      @RequestParam(value="startDate",required=false) Long startDate, 
      @RequestParam(value="endDate",required=false) Long endDate 
      ) 
    { 
    } 

但是這些變量的值始終爲空。所以我檢查了文檔,搜索了類似的問題,但是我什麼也沒找到。

當然,我可以將綁定類型更改爲String,然後將其轉換爲Long,但在我看來這不是一個好的解決方案。這只是一個解決方法...

另一種方式,我看到人們使用包裝對象與@ModelAttribute註釋綁定它。如;

public class Wrapper 
{ 
public Long startDate; 
public Long endDate; 
} 

@RequestMapping("/history") 
    public ModelAndView historyList_GET(
      @ModelAttribute Wrapper dates 
      ) 
{ 
} 

但是這又是一個解決方法。

我在問這怎麼可能?爲什麼即使所有其他的引用類型都完美綁定,Long不會呢?是因爲我錯過了什麼嗎?

這些都是順便請求......

/history?endDate=144656539476 
/history?startDate=144656539476 
/history?startDate=144656539476&endDate=14499999999 
+1

你一定錯過了什麼,你的代碼提供運作良好,並預期參數的約束。你確定這個特定的方法在發送請求時執行嗎?順便說一句。 '@ ModelAttribute'用於稍微不同的情況 –

+0

當發出請求時執行方法,我確定它。至於我錯過什麼的部分,我也想過,但這是一個非常簡單的方法,它應該是有約束力的......我無法弄清楚爲什麼。 – paroxit

+0

您可以在某些公共存儲庫中重現問題嗎? –

回答

0

你的包裝類缺少setter方法。這工作對我的包裝類的

實際代碼: -

public class Wrapper { 
    public Long startDate; 
    public Long endDate; 

    public Long getStartDate() { 
     return startDate; 
    } 

    public void setStartDate(Long startDate) { 
     this.startDate = startDate; 
    } 

    public Long getEndDate() { 
     return endDate; 
    } 

    public void setEndDate(Long endDate) { 
     this.endDate = endDate; 
    } 

}