input.jsp页面加入这样的方式,将一个字符串提交到后台。
后台用SpringMVCTest.java处理它。但是这个处理是将字符串转换成对象,所以我们得去配置EmployeeConverter自定义的对象。
package com.hust.springmvc.test;
import com.hust.springmvc.dao.EmployDao;
import com.hust.springmvc.entities.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
/**
* Created by yexx on 16-11-11.
*/
@Controller
public class SpringMVCTest {
@Autowired
private EmployDao employDao;
@RequestMapping(value = "/testConversionServiceConverter", method = RequestMethod.POST)
public String testConverter(@RequestParam("employee") Employee employee) {
System.out.print("save:" + employee);
employDao.save(employee);
return "redirect:/emps";
}
}
EmployeeConverter.java
package com.hust.springmvc.converters;
import com.hust.springmvc.dao.DepartmentDao;
import com.hust.springmvc.entities.Department;
import com.hust.springmvc.entities.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
/**
* Created by yexx on 16-11-11.
*/
@Component
public class EmployeeConverter implements Converter<String, Employee> {
@Autowired
private DepartmentDao departmentDao;
@Override
public Employee convert(String s) {
if (s != null) {
String[] vals = s.split("-");
if (vals != null && vals.length == 4) {
String lastName = vals[0];
String email = vals[1];
Integer gender = Integer.parseInt(vals[2]);
Employee employee = new Employee(null, lastName, email, gender, departmentDao.getDepartment(Integer.parseInt(vals[3])));
System.out.println(s + "--convert--" + employee);
return employee;
}
}
return null;
}
}
在SpringMVC的配置文件配置如下。配置conversionService,而且还要在mvc:annotation-driven配置一下conversion-service。
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
<!-- 配置 ConversionService -->
<bean id="conversionService"
class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<ref bean="employeeConverter"/>
</set>
</property>
</bean>
这样就能进行自定义数据转换器的功能了,会按照自定义的字符串的格式转换为相应的对象。
跟踪流程:
先在字符串进来的地方打断点,debug模式进入,找到resolveArgument,找到binder。
找到conversionService
找到最底下我们自己自定义的数据转换器,看到了包名了吧,还有String类型的。可以把他们加到watches,看到具体情况。
运行截图