表單中的日期 字符串和Javabean中的日期類型的屬性自動轉換


搞了一上午的bug最終還是因為自己springMVC的注解不熟悉的原因,特記錄。

在實際操作中經常會碰到表單中的日期 字符串和Javabean中的日期類型的屬性自動轉換, 而springMVC默認不支持這個格式的轉換,所以必須要手動配置, 自定義數據類型的綁定才能實現這個功能。

比較簡單的可以直接應用springMVC的注解@initbinder和spring自帶的WebDataBinder類和操作

 

有些類型的數據是無法自動轉換的,比如請求參數中包含時間類型的數據,無法自動映射到Controller里的Date參數。需要使用@initBinder注解為binder提供一個數據的轉換器,這個轉換器可以自己實現,也可以用spring官方的一些實現。比如:

復制代碼
package com.wang.action;

import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
 * 測試@initBinder注解
 * @author wlyfree
 */
@Controller
public class BinderAction {

    @RequestMapping("/sb2.do")
    public void doTest(@RequestParam(value="name")String name,@RequestParam(value="age")double age,@RequestParam(value="nowTime")Date nowTime){
        System.err.println("name:" + name);
        System.err.println("age:" + age);
        System.err.println("nowTime:" + nowTime);
    } 
    
    @InitBinder
    public void initBinder(WebDataBinder binder){
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
    }
}
復制代碼


免責聲明!

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



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