SpringMVC学习(六)——@InitBinder注解

本文介绍如何在Spring MVC中使用@initBinder注解解决日期类型等数据的自动转换问题。通过自定义数据转换器,实现了Controller层对特定格式日期参数的有效处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  有些类型的数据是无法自动转换的,比如请求参数中包含时间类型的数据,无法自动映射到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));
    }
}

 

转载于:https://www.cnblogs.com/douJiangYouTiao888/p/6765220.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值