springMvc接受日期类型参数处理


springMvc接受日期类型参数处理

这个问题,也即是springMvc如何进行参数类型的转换

方案1 initBinder

在controller中加入数据绑定


1 @InitBinder  
2 public void initBinder(WebDataBinder binder) {  
3 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");  
4 dateFormat.setLenient(false);  
5 binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));   //true:允许输入空值,false:不能为空值

方案2 converter

以把client传过来一个String类型,转换为日期类型为例:

1.controller

复制代码
/**
     * 接收日期类型参数
     *     注意:
     *         springmvc 在接收日期类型参数时,如不做特殊处理 会出现400语法格式错误
     *  解决办法
     *      1.全局日期处理
     * 
     */
    
    @RequestMapping("/test")
    public String test(Date birthday){
        System.out.println(birthday);
        return "index";
    }
复制代码

2.自定义类型转换规则

SpringMvc提供了Converter接口,它支持从一个Object转换为另一个Object

复制代码
/**
 * 全局日期处理类
 * Convert<T,S>
 *         泛型T:代表客户端提交的参数 String
 *         泛型S:通过convert转换的类型
   
 */
public class DateConvert implements Converter<String, Date> {

    @Override
    public Date convert(String stringDate) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return simpleDateFormat.parse(stringDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

}
复制代码

3.注册自定义的类型转换类

复制代码
  <!-- 第三步:注册处理器映射器/处理器适配器 ,添加conversion-service属性-->
    <mvc:annotation-driven conversion-service="conversionService"/>
   
    <!-- 第二步: 创建convertion-Service ,并注入dateConvert-->
    <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <ref bean="dateConvert"/>
            </set>
        </property>
    </bean>
    <!-- 第一步:  创建自定义日期转换规则 -->   
    <bean id="dateConvert" class="zpark.convert.DateConvert"/>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值