JSTL formatDate和java.time.LocalDate

我无法弄清楚如何在JSP中显示java.time.LocalDate值。 在我的JSP中,我有这个:

  

std.datum的类型为java.time.LocalDate。 渲染jsp时,我得到了这个exception:

 javax.el.ELException: Cannot convert 2015-02-14 of type class java.time.LocalDate to class java.util.Date 

我假设它是转换?

谢谢,约翰。

是。 您可以使用fmt:parseDate进行转换,然后进行格式化。 以下示例

   

祝你好运。

这是一个老问题,但我发现在这种情况下最好做一个自定义tld:没有任何与String的双重转换。

做你自己的tld文件,然后覆盖FormatDate类。 最后,声明自己的自定义前缀并使用custom:formatDate而不是fmt:formatDate。

这是一个简化版本

JSP中的用法:

 <%@ taglib uri="/WEB-INF/custom" prefix="custom" %> ...  

WEB-INF / custom.tld文件

     FormatDate with java8 type  formatDate com.custom.tag.FormatDateTag empty   Date and/or time to be formatted.  value true true    Custom formatting style for dates and times.  pattern false true    

然后是java类标记文件

 public class FormatDateTag extends TagSupport { protected Temporal value; protected String pattern; private String var; private int scope; public FormatDateTag() { super (); init (); } private void init() { this.pattern = this.var = null; this.value = null; this.scope = PageContext.PAGE_SCOPE; } public void setVar(final String var) { this.var = var; } public void setScope(final String scope) { this.scope = Util.getScope (scope); } public void setValue(final Temporal value) { this.value = value; } public void setPattern(final String pattern) { this.pattern = pattern; } @Override public int doEndTag() throws JspException { String formatted = null; if (this.value == null) { if (this.var != null) { this.pageContext.removeAttribute (this.var, this.scope); } return EVAL_PAGE; } // Create formatter if (this.pattern != null) { final DateTimeFormatter formatter = DateTimeFormatter.ofPattern (this.pattern); formatted = formatter.format (this.value); } else { // no formatting locale available, use Date.toString() formatted = this.value.toString (); } if (this.var != null) { this.pageContext.setAttribute (this.var, formatted, this.scope); } else { try { this.pageContext.getOut ().print (formatted); } catch (final IOException ioe) { throw new JspTagException (ioe.toString (), ioe); } } return EVAL_PAGE; } @Override public void release() { init (); } }