SpringMVC-自定义Converter

(一)实现Converter接口,自定义一个转换器:

@Component
public class String2EmpConverter implements Converter {
	
	@Autowired
	DepartmentDao depDao;
	
	@Override
	//String format :"[email protected]"
	public Employee convert(String source) {
		Employee employee = new Employee();
		// TODO Auto-generated method stub
		if (source!=null && source.contains("-")) {
			String[] src = source.split("-");
			employee.setLastName(src[0]);
			employee.setEmail(src[1]);
			employee.setGender(Integer.parseInt(src[2]));
			employee.setDepartment(depDao.getDepartment(Integer.parseInt(src[3])));
		}
		return employee;
	}
}

(二)SpringDispatcherServlet中配置ServiceFactoryBean:

	
		
			
				
			
		
	

(三)添加注解驱动标签,并标注使用自行配置的ConversionService:

	
	

(四) JSP文件内增加提交表单:

	

(五)EmployeeController中处理请求:

	@RequestMapping("/quickAddEmp")
	public String quickAdd(@RequestParam("empInfo")Employee emp) {
		System.out.println("quick add emp : "+ emp);
		empDao.save(emp);
		return "redirect:/emps";
	}

(六) 成功添加Tom和Jerry:

SpringMVC-自定义Converter_第1张图片

你可能感兴趣的:(SpringMVC)