Springmvc 注解驱动格式化实例

public class User {private String name;
    //可将形如1980-09-01的字符串转换为Date类型的birthday属性中
    @DateTimeFormat(pattern = "yyyy-MM-dd")private Date birthday;
    //可将形如4,500.00的字符串转换到long类型的salary属性中
    @NumberFormat(pattern = "#,###.##")private long salary;

    public long getSalary() {return salary;
    }public void setSalary(long salary) {this.salary = salary;
    }public String getName() {return name;
    }public void setName(String name) {this.name = name;
    }public Date getBirthday() {return birthday;
    }public void setBirthday(Date birthday) {this.birthday = birthday;
    }
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>首页</title>
</head>
<body>
    <form action="<c:url value="/showuser.html" />">
        <table>
            <tr>
                    <td>
                        用户名:</td>
                    <td>
                        <input type="text" name="name"/>
                    </td>
            </tr>
            <tr>
                    <td>
                        生日:</td>
                    <td>
                        <input type="text" name="birthday"/>
                    </td>
            </tr>
            <tr>
                    <td>
                        工资:</td>
                    <td>
                        <input type="text" name="salary">
                    </td>
            </tr>
            <tr>
                    <td colspan="2">
                        <input type="submit" value="提交">
                    </td>
            </tr>
        </table>
    </form>
</body>
</html>
@RequestMapping("showuser")
public String showuser(User user){System.out.println(user.getName());
    System.out.println(user.getBirthday());
    System.out.println(user.getSalary());
    return "register";
}
<context:component-scan base-package="com.smart"/>
<!--替换原来默认的,FormattingConversionServiceFactory实现了格式化功能-->
<mvc:annotation-driven conversion-service="myconversionService"/>
<bean id="myconversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
      p:prefix="/WEB-INF/views/"
      p:suffix=".jsp"/>

占旭鹏
Thu Sep 06 00:00:00 GMT+08:00 2012
1123