SpringMVC中向服務器傳遞時間參數時出現的問題


1. 問題描述:

  今天在SpringMVC應用中上傳參數的時候遇到如下問題:

The request sent by the client was syntactically incorrect 

  這說明在提交的參數中,有的參數不符合服務器端數據要求。在排除其它參數沒問題的情況下,確定是其中的時間參數除了問題。

  客戶端傳送的時間參數如下所示:

  

  而接受此參數的字段是一個Date類型的數據:

  

  在Controller中使用自動裝箱:

  

  原因所在: 在裝箱過程中時間的參數的轉化出錯。

2. 問題解決

  2.1 方法一:

    在需要轉變時間的Controller中添加如下代碼:

@InitBinder
protected void initBinder(HttpServletRequest request,
            ServletRequestDataBinder binder) throws Exception {
    // DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    CustomDateEditor dateEditor = new CustomDateEditor(format, true);
    binder.registerCustomEditor(Date.class, dateEditor);
    super.initBinder(request, binder);
}

 

  2.2 方法二:

    在實體類中對應的時間字段上加上如下注釋:

@DateTimeFormat(pattern="yyyy-MM-dd")
private Date birthday;

    用這種方法的時候注意要引入joda-time.jar包,在Maven工程的pom.xml文件中加入如下依賴:

    

        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.9.4</version>
        </dependency>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM