2017-08-22 5 views
2

私はSpring MVCを初めて使用しています。だから、私はjava.util.Date用のカスタムフォーマッタを作成しようとしています。Springカスタムフォーマッタが動作しない

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/spring-create-formatter-annotation / – 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}" /> 
関連する問題