SpringMVC自定义类型转化器

2025-11-05 09:31:36

1、ConversionService是Spring类型转换体系的核心接口。可以利用ConversionServiceFactoryBean在Spring的IOC容器中定义一个ConversionService。

SpringMVC自定义类型转化器

2、我们自定义一个表单数据格式,直接转换成VO对象。输入的格式:GG-gwolf_2010@126.com-0-105。在表单输入框定义一个表单。

<%@page import="java.util.HashMap"%>

<%@page import="java.util.Map"%>

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

    

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

</head>

<body>

        <form action="testConversionServiceConverter" metho="post">

                <!-- lastname-email-gender-department.id 例如:GG-gwolf_2010@126.com-0-105 -->

                employee:<input type="text" name="employee"/>

                <input type="submit" value="Submit"/>

        </form>

</body>

SpringMVC自定义类型转化器

3、在SpringMVC控制层实现保存方法:

package com.gwolf.springmvc.handlers;

import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.validation.Errors;

import org.springframework.validation.FieldError;

import org.springframework.web.bind.WebDataBinder;

import org.springframework.web.bind.annotation.InitBinder;

import org.springframework.web.bind.annotation.ModelAttribute;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RequestParam;

import com.gwolf.springmvc.dao.DepartmentDao;

import com.gwolf.springmvc.dao.EmployeeDao;

import com.gwolf.springmvc.domain.Employee;

@Controller

public class EmployeeHandler {

        @Autowired

        private EmployeeDao employeeDao;

        

        @Autowired

        private DepartmentDao departmentDao;

        

        @RequestMapping("/testConversionServiceConverter")

        public String testConverter(@RequestParam("employee") Employee employee) {

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

                employeeDao.save(employee);

                return "emps";

        }

}

SpringMVC自定义类型转化器

4、现在表单的employee字符串是不能转化成VO对象的。我们需要实现一个转化器。

package com.gwolf.springmvc.domain;

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

import org.springframework.stereotype.Component;

@Component

public class EmployeeConverter implements Converter<String, Employee>{

        @Override

        public Employee convert(String source) {

                if(source!=null) {

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

                        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);

                                return employee;

                        }

                }

                return null;

        }

        

}

SpringMVC自定义类型转化器

5、在SpringMVC配置文件中注册上面声明转化器:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

        xmlns:context="http://www.springframework.org/schema/context"

        xmlns:mvc="http://www.springframework.org/schema/mvc"

        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd

                http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd

                http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">

        <!-- 配置自动扫描的包 -->

        <context:component-scan base-package="com.gwolf.springmvc">

        </context:component-scan>

        

        <!-- 配置视图解析器,如何把handler方法返回值解析为实际的物理视图 -->

        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

                <property name="prefix" value="/WEB-INF/views/"></property>

                <property name="suffix" value=".jsp"></property>

        </bean>

        

        <bean class="org.springframework.web.servlet.view.BeanNameViewResolver">

                <property name="order" value="100"></property>

        </bean>

        

        <mvc:interceptors>

                <mvc:interceptor>

                        <mvc:mapping path="/springmvc/helloworld"></mvc:mapping>

                        <bean class="com.gwolf.springmvc.interceptors.SecondInterceptor"></bean>

                </mvc:interceptor>

                

                <bean class="com.gwolf.springmvc.interceptors.FirstInterceptor"></bean>

        </mvc:interceptors>

        

        <bean id="messageSource" 

                class="org.springframework.context.support.ResourceBundleMessageSource">

                <property name="basename" value="i18n"></property>

        </bean>

        

        <mvc:view-controller path="/success" view-name="success"/>

        

        <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>

        

        <mvc:default-servlet-handler/>

        

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

                <property name="converters">

                        <set>

                                <ref bean="employeeConverter"/>

                        </set>

                </property>

        </bean>

        

        

        

</beans>

SpringMVC自定义类型转化器

6、启动程序,提交表单,查看程序是否转化成功。控制层已经正确的打印了vo对象的值。

SpringMVC自定义类型转化器

SpringMVC自定义类型转化器

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢