当前位置:网站首页>JSTL 自定义标签

JSTL 自定义标签

2022-06-11 13:48:00 梁云亮

说明

JSTL默认不支持LocalDate和LocalDateTime,在JSP中自定义显示LocalDate和LocalDateTime,需要通过自定义标签实现。

第一步:创建具体进行转换的工具类

  • LocalDateTimeFormatter
public class LocalDateTimeFormatter {
    
    public static String formatLocalDateTime(LocalDateTime localDateTime, String pattern) {
    
        return localDateTime.format(DateTimeFormatter.ofPattern(pattern));
    }
}
  • LocalDateFormatter
public class LocalDateFormatter {
    
    public static String formatLocalDate(LocalDate localDate, String pattern) {
    
        return localDate.format(DateTimeFormatter.ofPattern(pattern));
    }
}

第二步:在WEB-INF目录下创建tld文件

<?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://wego.com/format</uri>

    <function>
        <name>formatLocalDateTime</name>
        <function-class>com.wego.formatter.LocalDateTimeFormatter</function-class>
        <function-signature>java.lang.String formatLocalDateTime(java.time.LocalDateTime, java.lang.String)</function-signature>
    </function>

    <function>
        <name>formatLocalDate</name>
        <function-class>com.wego.formatter.LocalDateFormatter</function-class>
        <function-signature>java.lang.String formatLocalDate(java.time.LocalDate, java.lang.String)</function-signature>
    </function>
</taglib>

第三步:测试

  • 服务器端数据
request.setAttribute("localDate", LocalDate.now());
request.setAttribute("localDateTime", LocalDateTime.now());
  • 页面使用
日期:${
    f:formatLocalDate(localDate, 'yyyy-MM*dd')}
日期时间:${
    f:formatLocalDateTime(localDateTime, 'yyyy-MM-dd HH:mm:ss')}
原网站

版权声明
本文为[梁云亮]所创,转载请带上原文链接,感谢
https://hcshow.blog.csdn.net/article/details/125214591