>  기사  >  Java  >  SpringMvc는 날짜 양식 제출을 받아 자동으로 Date 유형 메소드로 변환합니다.

SpringMvc는 날짜 양식 제출을 받아 자동으로 Date 유형 메소드로 변환합니다.

无忌哥哥
无忌哥哥원래의
2018-07-19 11:21:154482검색

사용자는 생일(날짜) 속성을 가지고 있습니다. 사용자가 등록할 때 날짜를 선택한 다음 양식을 제출하면 됩니다. Spring mvc는 오류를 보고할 수 있으며 이는 문자열을 날짜 유형으로 변환할 수 없음을 의미합니다.

  • 엔티티 클래스에 날짜 형식 주석 추가

    @DateTimeFormat(pattern = "yyyy-MM-dd")  
    private Date birthday;
  • 컨트롤러에 데이터 바인딩 코드 조각 추가

    //将字符串转换为Date类
    @InitBinder
    public void initBinder(WebDataBinder binder, WebRequest request) {
        //转换日期格式
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 注册自定义的编辑器
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
        
    }

  • 방법 3: 전역 날짜 유형 변환기 구현 및 구성

package nuc.ss.wlb.core.web;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.context.request.WebRequest;

public class CustomDateEdtor implements WebBindingInitializer {

    
    public void initBinder(WebDataBinder binder, WebRequest request) {
        // TODO Auto-generated method stub
        //转换日期格式
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

}

//并在spingMVC配置文件进行配置

<!-- 配置全局日期转换器 -->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="webBindingInitializer">    
            <bean class="nuc.ss.wlb.core.web.CustomDateEdtor"/>
        </property>
    </bean>
  • 방법 4: JSP 페이지 구성 또는 Freemark

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

에서 구성

위 내용은 SpringMvc는 날짜 양식 제출을 받아 자동으로 Date 유형 메소드로 변환합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.