2017-08-22 71 views
2

我是Spring MVC的新手,剛剛遇到了Spring自定義格式化程序。所以我正在嘗試爲java.util.Date創建一個自定義格式化程序。春季自定義格式化程序不能正常工作

MyDateFormatter.java

public class MyDateFormatter implements Formatter<Date>{ 

    private String pattern = "yyyyMMdd"; 


    @Override 
    public String print(Date date, Locale locale) { 
     if (date == null) { 
      return ""; 
     } 
     return getDateFormat(locale).format(date); 
    } 

    @Override 
    public Date parse(String formatted, Locale locale) throws ParseException { 
     if (formatted.length() == 0) { 
      return null; 
     } 
     return getDateFormat(locale).parse(formatted); 
    } 

    protected DateFormat getDateFormat(Locale locale) { 
     DateFormat dateFormat = new SimpleDateFormat(this.pattern, locale); 
     dateFormat.setLenient(false); 
     return dateFormat; 
    } 
} 

TestFormatterController.java

@Controller 
public class TestFormatterController { 
    @RequestMapping(value="/testFormatter") 
    public String getDate(ModelMap map){ 
     Date date = new Date(); 
     map.put("date", date); 
     return "testFormatter"; 
    } 
} 

testFormatter.jsp

<h1>${date}<h1> 

配置

<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> 
     <property name="formatters"> 
      <set> 
       <bean class="mypackge.MyDateFormatter"> 
      </set> 
     </property> 
    </bean> 

輸出不在yyyyMMdd中。你能告訴我我錯過了什麼嗎?

+0

你如何讓春天知道你的格式化程序? – StanislavL

+0

@StanislavL我需要做什麼以外的配置在我的例子中提到的配置? – Aman

+0

http://www.logicbig.com/tutorials/spring-framework/spring-web-mvc/spring-define-formatter/和http://www.logicbig.com/tutorials/spring-framework/spring-web- MVC /彈簧創建-格式的註釋/ – StanislavL

回答

0

春天不會調用格式化,當我們直接打印像$ {}日期的對象,我們必須使用<spring:eval>代替。我改變了我的JSP以下,現在它按預期工作:

<%@ include file="/WEB-INF/jsp/common/taglibs.jsp"%> 
<spring:eval expression="date" /> 
0

嘗試這種方式

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> 
    <fmt:formatDate pattern="yyyy-MM-dd" value="${now}" />