spring mvc 3 date

Spring 2012. 3. 19. 19:56
화면에 특정 날짜형식으로 입력 받고, Controller에서 입력받은 값을 특정 날짜 형식으로 Model에 Binding하고 입력사항 검사도 할려면 다음과 같이 하면 될것 같다.

spring context에 'config.properties' file을 추가하고
<bean id="propertyPlaceHolder"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:config.properties</value>
</list>
</property>
<property name="fileEncoding" value="UTF-8"/> 
</bean>

'config.properties'에 다음과 같이 date format pattern을 넣고
date.format=yyyy-MM-dd
datetime.format=yyyy-MM-dd HH:mm:ss

joda-time-2.1.jar 파일을 다운받고 다음과 같이 model에 @DateTimeFormat(parrent="${date.format}")를 입력해서 property파일과 연동 한 후
public class DateModel {
private String name;
@DateTimeFormat(pattern="${date.format}")
private Date registerDate;

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getRegisterDate() {
return registerDate;
}
public void setRegisterDate(Date registerDate) {
this.registerDate = registerDate;
}
@Override
public String toString() {
return "DateModel [name=" + name + ", registerDate=" + registerDate
+ "]";
}
}
 
jsp파일에서 다음과 같이 입력 받거나 출력하면 된다.
<form:input path="registerDate"/> 

<spring:eval expression="dateModel.registerDate" />  


@DateTimeFormat를 사용하지 않은 Model의 날짜 형식을 다르게 해서 출력하고 property file의 내용을 참고 할려면... spring tag가 없는것 같아서 다음과 같이 해야 할것 같다..
Controller에 다음의 코드를 넣고

@Value("${date.format}")
private String dateFormat;

@ModelAttribute("dateFormat")
public String dateFormat() {
return this.dateFormat;
}

jsp파일에서 다음과 같이 사용한다.(깔금한 방법은 아니다. spring tag로 지원이 되어야 할것 같다. 아니면 다른 방법이 있는지... 찾아 봐야 할듯...)
<fmt:formatDate pattern="${dateFormat}" value="${communication.registerDate}"/> 


이렇게 하면 config.properties안의 날짜형식 pattern 값으로 날짜 형식을 관리 할 수 있을듯...
jQuery의 datepicker를 사용하는 부분은 다음과 같은 .js파일을 만들고 datepicker사용하는 부분에서 include해서 사용하고 국가별로 변경해서 사용하면 될듯...
jQuery(function ($) {
    $.datepicker.regional['ko'] = {
        monthNames: ['. 01', '. 02', '. 03', '. 04', '. 05', '. 06', '. 07', '. 08', '. 09', '. 10', '. 11', '. 12'],
        dayNamesMin: ['일', '월', '화', '수', '목', '금', '토'],
        showMonthAfterYear: true,
        dateFormat: 'yy-mm-dd',
        showOn: 'both',
        buttonImage: 'http://static.xxx.co.kr/calendar.gif',
        buttonImageOnly: true,
        changeYear: true
        //        yearSuffix: '',
        //        firstDay: 0,
        //        weekHeader: 'Wk',
        //        closeText: '닫기',
        //        prevText: '이전달',
        //        nextText: '다음달',
        //        currentText: '오늘',
    };


    $.datepicker.setDefaults($.datepicker.regional['ko']);
});
 
Posted by 파이팅야
,