程序员社区

SpringMvc中自定义类型转换器

@Data
public class User implements Serializable {
    private String uname;
    private int age;
    private Date date;
}
<form action="param/saveUser" method="post">
    用户姓名:<input type="text" name="uname"/><br>
    用户年龄:<input type="text" name="age"/><br>
    用户生日:<input type="text" name="date"/><br>
    <input type="submit" value="提交"/>
</form>

将字符串转换为日期实现类:

public class StringToDateConverter implements Converter<String,Date> {
    public Date convert(String s) {
        if(s==null){
            throw new RuntimeException("请您传入数据");
        }
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        try {
            //把字符串转换为日期
            df.parse(s);
        } catch (ParseException e) {
            throw new RuntimeException("数据类型转换出错");
        }
        return null;
    }
}

在springmvc.xml中配置自定义转换器:

<!--配置自定义转换器-->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <set>
            <bean class="com.hh.utils.StringToDateConverter"/>
        </set>
    </property>
</bean>

<!--开启Springmvc注解支持-->
<mvc:annotation-driven conversion-service="conversionService"/>

在这里插入图片描述

赞(0) 打赏
未经允许不得转载:IDEA激活码 » SpringMvc中自定义类型转换器

相关推荐

  • 暂无文章

一个分享Java & Python知识的社区