Programming > Spring Framework

[spring] @InitBinder 파라메터 바인딩 - WebBindingInitializer

Annotation을 통한 Controller 파라메터 바인딩 (모델바인딩)

1. Controller 안에 개별적으로 @InitBinder 설정

@Controller
public class IndexController {

    @InitBinder
    public void initBinder(WebDataBinder dataBinder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        dateFormat.setLenient(false);
        dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }
    @RequestMapping(value="/login ")
    public String loginPolice( Model model, HttpServletRequest req, @RequestParam Date inDate, @RequestParam String noStr) throws Exception {

        System.out.println("inDate=" + inDate);
        System.out.println("noStr=" + noStr);
       
         return "login/login";
    }
}

2. @ControllerAdvice 를 통한 전체 Controller 대상 설정

@ControllerAdvice
public class ControllerAdvisor {

    @InitBinder
    public void customBinding(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(false));
    }
}

3. WebBindingInitializer 를 통한 전체 Controller 대상 설정

public class MyBindingInitializer implements WebBindingInitializer {

@Override
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(false));
    }
}

※ 주의 ※ <mvc:annotation-driven/> 에의해 Annotation HandlerAdapter 를 자동 매핑하는데
    global propertyEditor는 이 시점에서 작동하지 않는다. 
   그래서 반드시 <mvc:annotation-driven/> 전에 bean을 선언해야 에러가 안난다.

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
   <property name="webBindingInitializer">
       <bean class="com.emunhi.web.MyBindingInitializer"/>
    </property>
</bean>
※※ 아래에 위치 ※※
<mvc:annotation-driven/>