SpringMVC——自定义类型转化器

自定义转换器主要是实现String类型的数据转换为其他类型的,当浏览器提交数据的时候,request中的数据都是以String类型存在的,Spring会做一些类型转换,将这些数据转换成我们所需要的数据类型(int、float等)。如SpringMVC——请求参数的绑定中所示,String类型的2020/01/01会被Spring转换为Date类型数据,而String类型的2020-01-01则无法自动转换为Date类型的数据,这个时候就需要我们自定义类型转换器来满足我们的需要。

示例代码

编写JSP代码

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

<html>
    <head>
        <title>requestMapping的使用</title>
    </head>
    <body>
        <!--自定义类型转换器-->
        <a href="account/deleteAccount?date=2020-01-01">根据日期2020-01-01删除账户</a><br/>
    </body>
</html>

编写Controller代码

package com.liang.controller;

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

import java.util.Date;

@Controller("accountController")
@RequestMapping(path = "/account")
public class AccountController {

    /**
     * 更新账户
     * @return
     */
    @RequestMapping(path = "/deleteAccount")
    public String deleteAccount(Date date){
        System.out.println("删除了账户..."+date);
        return "success";
    }
}

编写自定义转换器代码

  • 定义一个类,实现Converter接口
package com.liang.utils;

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

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class StringToDateConverter implements Converter<String, Date> {

    @Override
    public Date convert(String s) {
        DateFormat dateFormat = null;
        try{
            if (s.isEmpty()){
                throw new NullPointerException("需要转换的数据为空");
            }
            dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date date = dateFormat.parse(s);
            return date;
        }catch (Exception e){
            throw  new RuntimeException("输入日期有误");
        }
    }
}
  • 在springmvc配置文件中配置类型转换器
    <!--配置自定义类型转换器:将自定义的类型转换器注册到类型转换服务中去-->
    <!--配置类型转换器工厂bean-->
    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <!--给工厂注入一个新的类型转换器-->
        <property name="converters">
            <set>
                <!--配置自定义类型转换器-->
                <bean class="com.liang.utils.StringToDateConverter"></bean>
            </set>
        </property>
    </bean>
  • annotation-driven标签中引用配置的配型转换器服务
    <!--引用自定义类型转换器-->
    <mvc:annotation-driven conversion-service="conversionService"/>

Converter<S, T>接口

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package org.springframework.core.convert.converter;

import org.springframework.lang.Nullable;

@FunctionalInterface
public interface Converter<S, T> {
    @Nullable
    T convert(S var1);
}

其中参数 S:代表需要进行转换的参数的数据类型
T:代表转换后的数据类型

<mvc;annotation-driven>说明

在SpringMVC的各个组件中,处理器映射器、处理器适配器、视图解析器称为SpringMVC的三大组件。
使用mvc:annotation-driven自动加载处理器映射器和处理器适配器,所以可在SpringMVC的配置文件中使用此标签代替注解处理器和适配器的配置。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章