如何在JSF Date上以自定义格式显示Timestamp(或<h:commandButton>)?

我正在使用JSF 1.1

最佳答案

JSF <h:commandButton>不支持转换器,也不支持任何文本子代。您可能需要使用一些辅助bean方法来执行该工作,

<h:commandButton ... value="#{bean.dateInCustomizedFormat}" />




public String getDateInCustomizedFormat() {
    return new SimpleDateFormat("yyyy-MM-dd").format(date);
}


或为此创建可重复使用的自定义EL函数:

<%@taglib prefix="my" uri="http://example.com/el/functions" %>
...
<h:commandButton ... value="#{my:formatDate(bean.date, 'yyyy-MM-dd')}" />




package com.example.el;

import java.text.SimpleDateFormat;
import java.util.Date;

public final class Functions{

    private Functions() {
        // Hide constructor.
    }

    public static String formatDate(Date date, String pattern) {
        Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
        return new SimpleDateFormat(pattern, locale).format(date);
    }

}


/WEB-INF/functions.tld(考虑到JSF 1.1,我假设您仍在使用JSP,而不是Facelets):

<?xml version="1.0" encoding="UTF-8" ?>
<taglib
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
    version="2.1">

    <tlib-version>1.0</tlib-version>
    <short-name>Custom Functions</short-name>
    <uri>http://example.com/el/functions</uri>

    <function>
        <name>formatDate</name>
        <function-class>com.example.el.Functions</function-class>
        <function-signature>java.lang.String formatDate(java.util.Date, java.lang.String)</function-signature>
    </function>
</taglib>


(注意:如果您使用的是Servlet 2.4 / JSP 2.0,请分别用2_12.1替换2_02.0

关于java - 如何以自定义格式在JSF按钮上显示日期作为标签?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12419554/

10-11 22:12
查看更多