Spring MVC 之自定义类型转换器

目录

一、错误演示

二、错误原因

三、解决方法


一、错误演示

问题描述:

        当我们在前端页面给后台传入数据时,发生了HTTP Status 400 – Bad Request的错误,错误信息如下:

HTTP Status 400 – Bad Request

Type Status Report

Description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).

        错误的截图如下:

 问题探索:

        查看JSP表单页面,发现我们表单中生日给的数据类型是text,而用户实体类中的生日是Date类型,由此产生了是否是数据类型转换失败导致的想法。

         于是,我们将表单中的生日修改成日期类型,看看能否成功。结果不如人意,还是失败了。

 

二、错误原因

        其实,产生以上错误的原因是——数据类型转换失败。那为什么当我们修改了表单中的数据类型,依然不成功呢?原因很简单,

        只要是页面提交的数据,都是以String的形式传递给后台的。

三、解决方法

        基于以上原因,在此,我给出两个解决办法,供读者参考:

  1. 基于Spring框架内部会默认进行数据类型转换,将需要转换的日期格式按照默认书写方式:yyyy/MM/dd书写。
  2. 实现Converter的接口,完成自定义数据类型转换。

 1、最简单的方案,严格按照Spring框架规定的日期格式(yyyy/MM/dd)传参。

如下图,可以清楚的看到,保存用户“王昌龄”已经成功了,并且我将用户名和地址输出到了页面:

2、自定义数据类型转换

步骤:

  1. 创建一个方法,实现Convert接口,重写里面的convert方法
  2.  注册自定义类型转换器,在springmvc.xml配置文件中编写配置

代码:

1、StringToDateConverter.class

package cn.guohai.utils;


import com.mysql.jdbc.StringUtils;
import org.springframework.core.convert.converter.Converter;

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

/**
 * @author xuguohai
 * @version 1.0
 * 2022/7/18
 * 主要功能:
 * 实现字符串与日期之间的转换
 */
public class StringToDateConverter implements Converter<String,Date> {
    @Override
    public Date convert(String source) {
        if (StringUtils.isNullOrEmpty(source)){
            throw new RuntimeException("输入的参数为空!!");
        }
        try {

            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            // 返回解析后的字符串
            return sf.parse(source);
        }catch (Exception e){
            throw new RuntimeException("类型转换错误!!");
        }
    }
}

2、springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation=" http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 开启注解扫描,只扫描controller的注解,别的不扫描-->
    <context:component-scan base-package="cn.guohai">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--配置视图解析器-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- JSP文件所在的目录-->
        <property name="prefix" value="/WEB-INF/pages/"/>
        <!-- 文件的后缀名-->
        <property name="suffix" value=".jsp"/>
    </bean>


    <!-- 注册自定义类型转换器-->
    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="cn.guohai.utils.StringToDateConverter"/>
            </set>
        </property>
    </bean>

    <!--开启SpringMVC注解支持-->
    <mvc:annotation-driven conversion-service="conversionService"/>
</beans>

从下图中,可以看到,即使我们使用yyyy-MM-dd,服务器依然可以正常解析。

        至此,自定义类型转换器介绍结束,本文主要由一个字符串转换异常出发,引出了自定义类型转换器,并实现了其功能。如果有错误的地方,望读者批评指定,共同进步!

路漫漫其修远兮,吾将上下而求索。                ---屈原

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值