场景:spring mvc 中 jsp 页面向后台传入的数据类型都是 String,这里将 String 转换成 Date 对象

  1. 表单页面与显示效果:registerForm.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Register</title>
</head>
<body>
 
<h3>Register Page</h3>
<form action="register" method="post">
    <table>
        <tr>
            <td><label>Login Name:</label></td>
            <td><input type="text" id="loginname" name="loginname"></td>
        </tr>
        <tr>
            <td><label>Birthday:</label></td>
            <td><input type="text" id="birthday" name="birthday"></td>
        </tr>
        <tr>
            <td><input type="submit" value="Register"></td>
        </tr>
    </table>
</form>
 
</body>
</html>

  1. 成功页面:success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Success</title>
</head>
<body>
 
<h3>You are success</h3>
 
</body>
</html>
  1. 控制器:UserController.java

  1. 类型转换器:StringToDateConverter.java

  1. spring mvc 配置文件添加转换器
<!-- 装载自定义的类型转换器 -->
    <mvc:annotation-driven conversion-service="conversionService"/>
 
    <!-- 自定义的类型转换器 -->
    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <list>
                <bean class="com.demo.converter.StringToDateConverter" p:datePattern="yyyy-MM-dd"></bean>
            </list>
        </property>
    </bean>
  1. 结果