Facelets and JSTL (Converting a Date to a String for use in a field)

前端 未结 2 1898
天命终不由人
天命终不由人 2020-12-03 23:48

I need to convert a Date to a String within a page (I dont want to add loads of toStrings to my domain model so adding to the bean is not an option).



        
2条回答
  •  伪装坚强ぢ
    2020-12-04 00:22

    Indeed, you cannot use the "good old" JSTL in Facelets anymore the way as you would do in JSP. Facelets only supports a limited subset of JSTL (and has it already builtin, the JSTL JAR file is in fact superfluous).

    You're forced to write a custom tag or better, a custom EL function, for this purpose.

    Let's assume that we want to be able to do this:

    
    

    Roughly said thus the same what the JSTL tag can do, but then in flavor of an EL function so that you can use it everywhere without the need for an "intermediating" tag. We want it to take 2 arguments, a Date and a SimpleDateFormat pattern. We want it to return the formatted date based on the given pattern.

    First create a final class with a public static method which does exactly that:

    package com.example.el;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    public final class Formatter {
    
        private Formatter() {
            // Hide constructor.
        }
    
        public static String formatDate(Date date, String pattern) {
            return new SimpleDateFormat(pattern).format(date);
        }
    
    }
    

    Then define it as a facelet-taglib in /META-INF/formatter.taglib.xml:

    
    
    
    
        http://example.com/el/formatter
        
            formatDate
            com.example.el.Formatter
            String formatDate(java.util.Date, java.lang.String)
            
    
    

    Then familarize Facelets with the new taglib in the existing /WEB-INF/web.xml:

    
        facelets.LIBRARIES
        /META-INF/formatter.taglib.xml
    
    

    (note: if you already have the facelets.LIBRARIES definied, then you can just add the new path commaseparated)

    Then define it in the Facelets XHTML file as new XML namespace:

    
    

    Finally you can use it as intended:

    
    

    Hope this helps.

提交回复
热议问题