转换之术:解析Spring MVC中类型转换器的实际运用

简介: 转换之术:解析Spring MVC中类型转换器的实际运用


类型转换器

在 SpringMVC 框架中,类型转换器(Type Converter)用于将客户端传递的字符串类型的请求参数转换为控制器方法参数所需要的具体类型。它允许我们在处理请求时,将请求中的字符串参数转换为目标参数的实际类型,以便更方便地进行处理和操作。

SpringMVC 提供了一个 org.springframework.core.convert.converter.Converter 接口,可以通过实现该接口来自定义类型转换器。此外,SpringMVC 还内置了一些常见的类型转换器,可以满足大部分的需求。

以下是 SpringMVC 中常见的类型转换器:

  1. String to 基本数据类型:用于将字符串转换为基本数据类型,例如将 “123” 转换为 int 类型。
  2. 基本数据类型 to String:用于将基本数据类型转换为字符串,例如将 int 类型的 123 转换为 “123”。
  3. String to Enum:用于将字符串转换为枚举类型。
  4. Enum to String:用于将枚举类型转换为字符串。
  5. String to Date/Time:用于将字符串转换为日期或时间类型。
  6. Date/Time to String:用于将日期或时间类型转换为字符串。
  7. String to Collection:用于将字符串转换为集合类型。
  8. Collection to String:用于将集合类型转换为字符串。

自定义类型转换器

package world.xuewei.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Date;
/**
 * 测试类型转换器
 *
 * @author 薛伟
 * @since 2023/10/30 16:18
 */
@Controller
public class ConvertController {
    @RequestMapping("/convert")
    public String convert(Date date) {
        System.out.println(date);
        return "index";
    }
}

上面的控制器方法是有问题的,SpringMVC 默认是无法处理字符串转时间类型的。所以我们以此为场景开发自定义类型转换器。

编写转换器

package world.xuewei.config;
import org.springframework.core.convert.converter.Converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * 测试类型转换器
 *
 * @author 薛伟
 * @since 2023/10/30 16:18
 */
public class MyDateConvert implements Converter<String, Date> {
    @Override
    public Date convert(String s) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = null;
        try {
            parse = simpleDateFormat.parse(s);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        return parse;
    }
}

Spring 配置文件

<?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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!-- 配置注解扫描路径 -->
    <context:component-scan base-package="world.xuewei"/>
    <!-- 引入 Spring MVC 核心功能 -->
    <mvc:annotation-driven conversion-service="serviceFactoryBean"/>
    <!-- 自定义日期类型转换器 -->
    <bean id="convert" class="world.xuewei.config.MyDateConvert"/>
    <!-- 注册类型转换器 -->
    <bean id="serviceFactoryBean" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <ref bean="convert"/>
            </set>
        </property>
    </bean>
</beans>

SpringMVC 默认日期转换

在 SpringMVC 中,默认的字符串到日期类型的转换是通过 org.springframework.format.annotation.DateTimeFormat 注解实现的。你可以在方法参数或模型属性上使用该注解来指定日期的格式,以便在接收请求参数时将字符串转换为日期对象。

下面是一个示例,演示如何使用 @DateTimeFormat 注解将字符串转换为 java.util.Date 类型:

@RequestMapping("/example")
public String exampleMethod(@RequestParam("date") @DateTimeFormat(pattern = "yyyy-MM-dd") Date date) {
    // 处理date参数
    return "response";
}


相关文章
|
18天前
|
XML 安全 前端开发
Spring Security 重点解析(下)
Spring Security 重点解析
37 1
|
18天前
|
缓存 前端开发 Java
【框架】Spring 框架重点解析
【框架】Spring 框架重点解析
32 0
|
18天前
|
安全 NoSQL Java
Spring Security 重点解析(上)
Spring Security 重点解析
34 1
|
4天前
|
存储 数据处理 Python
Python中的字典(Dictionary)类型:深入解析与应用
Python中的字典(Dictionary)类型:深入解析与应用
|
5天前
|
存储 JSON 前端开发
利用Spring MVC开发程序2
利用Spring MVC开发程序
13 1
|
5天前
|
设计模式 JSON 前端开发
利用Spring MVC开发程序1
利用Spring MVC开发程序
17 0
|
5天前
|
存储 前端开发 Java
Spring MVC
Spring MVC
16 2
|
8天前
|
测试技术 持续交付 数据处理
Python动态类型深度解析与实践
Python动态类型深度解析与实践
395 1
|
11天前
|
域名解析 网络协议
【域名解析 DNS 专栏】DNS 记录类型全解析:A、MX、CNAME 与更多
【5月更文挑战第22天】DNS记录类型包括A、MX、CNAME等,用于确保域名与网络资源准确关联。A记录将域名指向IPv4地址,MX记录指定邮件服务器,CNAME则用于创建域名别名。其他记录如NS记录指定名称服务器,TXT记录用于验证和设置策略,SRV记录定义服务位置。正确配置DNS记录对网络运行至关重要,需注意信息准确性和及时更新。理解和运用这些记录能优化网络环境,支持各种在线服务。
【域名解析 DNS 专栏】DNS 记录类型全解析:A、MX、CNAME 与更多
|
15天前
|
XML 数据格式
XML Schema 复杂元素类型详解:定义及示例解析
在XML Schema(XSD)中,复杂元素包含其他元素和/或属性,分为4类:空元素、仅含元素、仅含文本和既含元素也含文本。定义复杂元素可通过直接声明或引用预定义的复杂类型。复杂空元素仅含属性,而仅含元素的类型则只包含其他子元素。XSD提供了`&lt;xs:sequence&gt;`、`&lt;xs:all&gt;`、`&lt;xs:choice&gt;`等指示器来规定元素顺序和出现次数,以及`&lt;xs:attributeGroup&gt;`和`&lt;xs:group&gt;`来组织元素和属性。
177 7

推荐镜像

更多