天天看點

資料綁定和自定義轉化類型DataBinder/ConversionService資料綁定和自定義轉化類型DataBinder/ConversionService

資料綁定和自定義轉化類型DataBinder/ConversionService

-1. Spring MVC 主架構将 ServletRequest 對象及目标方

法的入參執行個體傳遞給 WebDataBinderFactory 執行個體,以創

建 DataBinder 執行個體對象

• 2. DataBinder 調用裝配在 Spring MVC 上下文中的

ConversionService 元件進行資料類型轉換、資料格式

化工作。将 Servlet 中的請求資訊填充到入參對象中

• 3. 調用 Validator 元件對已經綁定了請求消息的入參對象

進行資料合法性校驗,并最終生成資料綁定結果

BindingData 對象

• 4. Spring MVC 抽取 BindingResult 中的入參對象和校驗

錯誤對象,将它們賦給處理方法的響應入參

自定義轉化器

“conversionService”/> 會将自定義的 ConversionService 注冊到Spring MVC 的上下文中

第一種配置

資料綁定和自定義轉化類型DataBinder/ConversionService資料綁定和自定義轉化類型DataBinder/ConversionService

第二種配置

資料綁定和自定義轉化類型DataBinder/ConversionService資料綁定和自定義轉化類型DataBinder/ConversionService

轉化器元件示例 實作Converter接口

@Component
public class EmployeeConverter implements Converter<String, Employee> {

    @Override
    public Employee convert(String source) {
        if(source != null){
            String [] vals = source.split("-");
            //[email protected]
            if(vals != null && vals.length == ){
                String lastName = vals[];
                String email = vals[];
                Integer gender = Integer.parseInt(vals[]);
                Department department = new Department();
                department.setId(Integer.parseInt(vals[]));

                Employee employee = new Employee(null, lastName, email, gender, department);
                System.out.println(source + "--convert--" + employee);
                return employee;
            }
        }
        return null;
    }

}
           

繼續閱讀