【SpringMVC】数据处理-数据绑定流程分析


        SpringMVC主框架将ServletRequest对象及目标方法的入参实例传递给webDataBinderFactory实例,以创建

DataBinder实例对象DataBinder调用装配在SpringMVC上下文中的ConversionService组件进行数据类型转换,数据

格式化工作,将Servlet中的请求信息填充到入参对象中调用Validator组件对已经绑定了请求消息的入参对象进行数据

合法性校验,并最终生成数据绑定结果BindingData对象SpringMVC抽取Bin定Result中的入参对象和校验错误对象,

将他们赋给处理方法的相应入参

【SpringMVC】数据处理-数据绑定流程分析_第1张图片

【SpringMVC】数据处理-数据绑定流程分析_第2张图片

【SpringMVC】数据处理-数据绑定流程分析_第3张图片



input.jsp:

<formaction="testConversionServiceConverter"method="post">

      

       Employee:<inputtype="text"name="employee">

form>

控制器:

@Controller

publicclass SpringMVCTest {

    @Autowired

    private EmployeeDaoemployeeDao;

    @RequestMapping("/testConversionServiceConverter")

    publicString testConverter(@RequestParam("employee") Employeeemployee){

       System.out.println("save:"+employee);

       employeeDao.save(employee);

       return"redirect:/emps";

    }

}

上面控制器中,testConverter()接受的是字符串,如何转为实体对象呢?

下面在springmvc.xml中引入转换器:

<mvc:annotation-drivenconversion-service="conversionService">mvc:annotation-driven>

   

   

    <beanid="conversionService"class="org.springframework.context.support.ConversionServiceFactoryBean">

       <propertyname="converters">

           <set>

              <ref bean="employeeConverter"/>

           set>

       property>

    bean>

 

转换器:加上@Component后,类被标注为bean,相当于"employeeConverter" class="">

@Component

publicclass EmployeeConverter implements Converter {

    @Override

    public Employee convert(Stringsource) {

       if (source !=null) {

           String[] vals=source.split("-");

           //GG-[email protected]-0-105

           if (vals!=null &&vals.length==4) {

              String lastName=vals[0];

              String email=vals[1];

              Integer gender=Integer.parseInt(vals[2]);

              Department department=new Department();

              department.setId(Integer.parseInt(vals[3]));

             

              Employee employee =new Employee(null,lastName, email,gender, department);

              System.out.println(source+"--convert--"+employee);

              returnemployee;

           }

       }

       returnnull;

    }

}


你可能感兴趣的:(★★MVC)