Jsf的日期转换通过<f:convertDateTime/>来实现。
来个简单的例子,从页面输入指定格式的日期,提交后,在页面上输出。
页面:
<%@taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@page contentType="text/html;charset=gb18030"%>
<f:view>
<html>
<body>
<h:form>
<h3>Jsf之DateConverter</h3>
请输入日期:
<h:inputText value="#{user.birthday }" id="birthday" converterMessage="请输入一个正确的日期!">
<f:convertDateTime pattern="yyyy/mm/dd" />
</h:inputText>
<h:commandButton value="提交" action="#{user.dateConvert }"></h:commandButton>
<br>
<br>
<h:message for="birthday" style="color:red;"></h:message>
</h:form>
<br>
<br>
您输入的日期:
<h:outputText value="#{user.birthday }">
<f:convertDateTime pattern="yyyy/mm/dd" />
</h:outputText>
</body>
</html>
</f:view>
UserBean.java:
package com.jsf.test;
public class UserBean {
private Date birthday;
//gettter and setter...
public String dateConvert() {
System.out.println(this.birthday);
return "date-converter";
}
}
就一个属性,接收一个Date型的参数。
faces-config.xml:
<?xml version="1.0"?>
<!DOCTYPE faces-config PUBLIC
"-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.0//EN"
"http://java.sun.com/dtd/web-facesconfig_1_0.dtd">
<faces-config>
<!-- jsf date converter -->
<navigation-rule>
<from-view-id>/pages/jsf_dateConverter.jsp</from-view-id>
<navigation-case>
<from-outcome>date-converter</from-outcome>
<to-view-id>/pages/jsf_dateConverter.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<managed-bean>
<managed-bean-name>user</managed-bean-name>
<managed-bean-class>
com.jsf.test.UserBean
</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
</faces-config>
效果:
1.正常的
2.这样的,也可以转换:
3.错误的: