Spring MVC - 날짜 필드 바인딩
문자열, 숫자 및 부울 값을 나타내는 요청 매개 변수의 경우 Spring MVC 컨테이너가 상자에서 꺼내어 입력된 속성으로 이 매개 변수를 바인딩할 수 있습니다.
Spring MVC 컨테이너가 날짜를 나타내는 요청 매개 변수를 바인딩하도록 하는 방법은 무엇입니까?
말이 나온 김에 Spring MVC는 주어진 요청 매개변수의 유형을 어떻게 결정합니까?
감사합니다!
스프링 MVC는 주어진 요청 매개 변수의 유형을 어떻게 결정합니까?
Spring은 ServletRequestDataBinder를 사용하여 값을 바인딩합니다.프로세스는 다음과 같이 설명할 수 있습니다.
/**
* Bundled Mock request
*/
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("name", "Tom");
request.addParameter("age", "25");
/**
* Spring create a new command object before processing the request
*
* By calling <COMMAND_CLASS>.class.newInstance();
*/
Person person = new Person();
...
/**
* And then with a ServletRequestDataBinder, it binds the submitted values
*
* It makes use of Java reflection To bind its values
*/
ServletRequestDataBinder binder = new ServletRequestDataBinder(person);
binder.bind(request);
백그라운드에서 DataBinder 인스턴스는 내부적으로 명령 개체의 값 설정을 담당하는 BeanWrapperImppl 인스턴스를 사용합니다.get 속성 포함형식 메서드, 속성 형식을 검색합니다.
위에 제출된 요청을 보면(물론, 모의실험을 통해), Spring이 전화를 걸 것입니다.
BeanWrapperImpl beanWrapper = new BeanWrapperImpl(person);
Clazz requiredType = beanWrapper.getPropertyType("name");
그리고 나서.
beanWrapper.convertIfNecessary("Tom", requiredType, methodParam)
Spring MVC 컨테이너는 날짜를 나타내는 요청 매개 변수를 어떻게 바인딩합니까?
특수 변환이 필요한 데이터를 사용자 친화적으로 표현하는 경우 PropertyEditor For(예: java.util)를 등록해야 합니다.날짜는 13/09/2010이 무엇인지 모르기 때문에 당신은 봄을 말합니다.
봄, 다음 속성 편집기를 사용하여 이 인간 친화적인 날짜를 변환하십시오.
binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
public void setAsText(String value) {
try {
setValue(new SimpleDateFormat("dd/MM/yyyy").parse(value));
} catch(ParseException e) {
setValue(null);
}
}
public String getAsText() {
return new SimpleDateFormat("dd/MM/yyyy").format((Date) getValue());
}
});
convertIfRequired 메서드를 호출할 때 Spring은 제출된 값의 변환을 처리하는 등록된 PropertyEditor를 찾습니다.Property Editor를 등록하려면 다음 중 하나를 수행합니다.
스프링 3.0
@InitBinder
public void binder(WebDataBinder binder) {
// as shown above
}
올드 스타일 스프링 2.x
@Override
public void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
// as shown above
}
Arthur의 매우 완전한 답변에 추가하여, 단순한 날짜 필드의 경우 전체 속성 편집기를 구현할 필요가 없습니다.사용할 날짜 형식을 전달하는 CustomDateEditor를 사용하면 됩니다.
//put this in your Controller
//(if you have a superclass for your controllers
//and want to use the same date format throughout the app, put it there)
@InitBinder
private void dateBinder(WebDataBinder binder) {
//The date format to parse or output your dates
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
//Create a new CustomDateEditor
CustomDateEditor editor = new CustomDateEditor(dateFormat, true);
//Register it as custom editor for the Date type
binder.registerCustomEditor(Date.class, editor);
}
언급URL : https://stackoverflow.com/questions/3705282/spring-mvc-binding-a-date-field
'programing' 카테고리의 다른 글
Rest api - 단일 리소스 필드 업데이트 (0) | 2023.08.27 |
---|---|
jquery를 사용하여 스크롤바가 없는 브라우저 뷰포트의 높이와 너비를 가져오시겠습니까? (0) | 2023.08.27 |
XMLHttpRequest.responseType 설정이 갑자기 금지되었습니까? (0) | 2023.08.22 |
하위 요소에 영향을 주지 않고 배경 이미지의 불투명도 설정 (0) | 2023.08.22 |
민달팽이란 무엇입니까? (0) | 2023.08.22 |