java培训技术自定义类型转换器示例

发布时间:2021年03月10日作者:atguigu浏览次数:1,032

自定义类型转换器示例

         1)  需求:字符串转换为对象。

         2)  步骤:

  • 定义页面

java培训

  • 控制器方法

package com.atguigu.springmvc.crud.handlers;

 

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.RequestParam;

 

import com.atguigu.springmvc.crud.dao.EmployeeDao;

import com.atguigu.springmvc.crud.entities.Employee;

 

@Controller

public class TypeConversionHandler {

 

@Autowired

private EmployeeDao employeeDao ;

 

// String -> Employee 需要类型转换器帮忙

@RequestMapping(“/empAdd”)

public String empAdd(@RequestParam(value=”employee”) Employee employee){

System.out.println(“TypeConversionHandler – ” + employee);

employeeDao.save(employee);

return “redirect:/empList”;

}

}

  • 自定义类型转换器

package com.atguigu.springmvc.converter;

 

import org.springframework.core.convert.converter.Converter;

import org.springframework.stereotype.Component;

 

import com.atguigu.springmvc.crud.entities.Department;

import com.atguigu.springmvc.crud.entities.Employee;

 

/**

 * 将字符串转换为Employee对象类型

 */

@Component

public class StringToEmployeeConverter implements Converter<String, Employee> {

 

@Override

public Employee convert(String source) {

if(source!=null){

String[] strs = source.split(“-“);

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

String lastName = strs[0];

String email = strs[1];

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

Integer deptId = Integer.parseInt(strs[3]);

Department dept = new Department();

dept.setId(deptId);

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

System.out.println(source+”–converter–“+employee);

return employee ;

}

}

return null;

}

}

  • 声明类型转换器服务

java培训

  • <mvc:annotation-driven conversion-service=”conversionService“/> 会将自定义的ConversionService 注册到 Spring MVC 的上下文中。

想要了解跟多关于java培训课程内容欢迎关注尚硅谷java培训,尚硅谷除了这些技术文章外还有免费的高质量java培训课程视频供广大学员下载学习。


上一篇:
下一篇:
相关课程

java培训 大数据培训 前端培训

关于尚硅谷
教育理念
名师团队
学员心声
资源下载
视频下载
资料下载
工具下载
加入我们
招聘岗位
岗位介绍
招贤纳师
联系我们
全国统一咨询电话:010-56253825
地址:北京市昌平区宏福科技园2号楼3层(北京校区)

深圳市宝安区西部硅谷大厦B座C区一层(深圳校区)

上海市松江区谷阳北路166号大江商厦3层(上海校区)

武汉市东湖高新开发区东湖网谷(武汉校区)

西安市雁塔区和发智能大厦B座3层(西安校区)

成都市成华区北辰星拱青创园综合楼3层(成都校区)