string @InitBinder 使用

本文介绍如何在SpringMVC中使用@InitBinder注解实现自定义数据绑定,包括日期和字符串到整数类型的转换。通过具体示例代码展示了如何创建定制的数据编辑器。

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

在SpringMVC中,bean中定义了Date,double等类型,如果没有做任何处理的话,日期以及double都无法绑定。

解决的办法就是使用spring mvc提供的@InitBinder标签

 

 

@Controller

public class BoceController extends BaseController {

 

@InitBinder

public void initBinder(WebDataBinder binder) {

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

dateFormat.setLenient(false);

binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));

binder.registerCustomEditor(String.class,new StrToInteger());

}

}

 

 

package com.cloud.api.util;

 

import java.beans.PropertyEditorSupport;

 

public class StrToInteger extends PropertyEditorSupport{

 

@Override    

    public void setAsText(String text) throws IllegalArgumentException {    

        if (text == null || text.equals("")) {    

            text = "0";    

        }  

        //text 中获取请求对象

        //2. 将请求对象转化为 需要的对象

        

        Integer value = Integer.parseInt(text);

        //3 将转化的对象放入 setValue 方法中

        setValue(value);    

    }    

    

    @Override    

    public String getAsText() { 

    System.out.println("=++++++++++++++++++++++++++++++++");

        return getValue().toString();    

    }   

    

}

 

 

StrToInteger 这个类是在接收到post 提交的字段后,然后 把接收到的string 字符串,转化为 Integer 对象的方法。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值