前端传String字符串 后端使用enun枚举类出现错误

ops/2024/10/9 13:24:58/
情况 前端 String 后端 enum

前端
image.png
后端
image.png
报错

2024-05-31T21:47:40.618+08:00  WARN 21360 --- [nio-8080-exec-6] .w.s.m.s.DefaultHandlerExceptionResolver : 
Resolved [org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: 
Failed to convert value of type 'java.lang.String' to required type 'com.orchids.springmybatisplus.model.enums.Sex'; 
Failed to convert from type 
[java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam 
com.orchids.springmybatisplus.model.enums.Sex] for value '1']

问题出现在这个方法

    //根据性别查询学生 存在String --->转换为enums\@Operation(summary = "根据性别(类型)查询学生信息")@GetMapping("sex") //@RequestParam(required = false) required=false 表示参数可以没有public Result<List<Student>> StudentBySex(@RequestParam(required = false) Sex sex){LambdaQueryWrapper<Student> lambdaQueryWrapper = new LambdaQueryWrapper<>();lambdaQueryWrapper.eq(Student::getSex,sex);List<Student> list = studentService.list(lambdaQueryWrapper);return Result.ok(list);}

对应的枚举类

package com.orchids.springmybatisplus.model.enums;import com.baomidou.mybatisplus.annotation.EnumValue;
import com.fasterxml.jackson.annotation.JsonValue;/*** @Author qwh* @Date 2024/5/31 19:13*/
public enum Sex implements BaseEnum{MAN(0,"男性"),WOMAN(1, "女性");@EnumValue@JsonValueprivate Integer code;private String name;Sex(Integer code, String name) {this.code = code;this.name = name;}@Overridepublic Integer getCode() {return this.code;}@Overridepublic String getName() {return this.name;}
}
解决方法 一
  1. 编写StringToSexConverter方法
package com.orchids.lovehouse.web.admin.custom.converter;import com.orchids.lovehouse.model.enums.ItemType;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;@Component
public class StringToItemTypeConverter implements Converter<String, ItemType> {/*** 根据给定的代码字符串转换为对应的ItemType枚举。** @param code 代表ItemType枚举的代码字符串,该代码应该是整数形式。* @return 对应于给定代码的ItemType枚举值。* @throws IllegalArgumentException 如果给定的代码无法匹配到任何枚举值时抛出。*/@Overridepublic ItemType convert(String code) {// 遍历所有ItemType枚举值,查找与给定代码匹配的枚举for (ItemType value : ItemType.values()) {if (value.getCode().equals(Integer.valueOf(code))) {return value;}}// 如果没有找到匹配的枚举,抛出异常throw new IllegalArgumentException("code非法");}
}

将其注册到WebMvcConfiguration

package com.orchids.springmybatisplus.web.custom.config;import com.orchids.springmybatisplus.web.custom.converter.StringToSexConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;/*** @Author qwh* @Date 2024/5/31 22:06*/
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {@Autowiredprivate StringToSexConverter stringToItemTypeConverter;@Overridepublic void addFormatters(FormatterRegistry registry) {registry.addConverter(this.stringToItemTypeConverter);}
}

成功解决

  1. 当有很多种类型需要转换 例如`
    1. StringInteger`、
    2. StringDate
    3. StringBoolean
    • 就要写每一种转换方法 代码重用性不高
    • 于是就有了第二种方法
    • 使用[ConverterFactory](https://docs.spring.io/spring-framework/reference/core/validation/convert.html#core-convert-ConverterFactory-SPI)接口更为合适,这个接口可以将同一个转换逻辑应用到一个接口的所有实现类,因此我们可以定义一个BaseEnum接口,然后另所有的枚举类都实现该接口,然后就可以自定义ConverterFactory,集中编写各枚举类的转换逻辑了
    • 具体实现如下
    • 在编写一个BaseEnum接口
public interface BaseEnum {Integer getCode();String getName();
}
  • 让enums 包下的枚举都实现这个接口
package com.orchids.springmybatisplus.model.enums;import com.baomidou.mybatisplus.annotation.EnumValue;
import com.fasterxml.jackson.annotation.JsonValue;/*** @Author qwh* @Date 2024/5/31 19:13*/
public enum Sex implements BaseEnum{MAN(0,"男性"),WOMAN(1, "女性");@EnumValue@JsonValueprivate Integer code;private String name;Sex(Integer code, String name) {this.code = code;this.name = name;}@Overridepublic Integer getCode() {return this.code;}@Overridepublic String getName() {return this.name;}
}
  • 编写 StringToBaseEnumConverterFactory 实现接口 ConverterFactory
@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {@Overridepublic <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {return new Converter<String, T>() {@Overridepublic T convert(String source) {for (T enumConstant : targetType.getEnumConstants()) {if (enumConstant.getCode().equals(Integer.valueOf(source))) {return enumConstant;}}throw new IllegalArgumentException("非法的枚举值:" + source);}};}
}
  • 将其注册到WebMvcConfiguration
package com.orchids.springmybatisplus.web.custom.config;import com.orchids.springmybatisplus.web.custom.converter.StringToBaseEnumConverterFactory;
import com.orchids.springmybatisplus.web.custom.converter.StringToSexConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;/*** @Author qwh* @Date 2024/5/31 22:06*/
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {@Autowiredprivate StringToBaseEnumConverterFactory stringToBaseEnumConverterFactory;@Overridepublic void addFormatters(FormatterRegistry registry) {registry.addConverterFactory(this.stringToBaseEnumConverterFactory);}
}

第二种方法有这一个类就行了


http://www.ppmy.cn/ops/46276.html

相关文章

华为 2024 届实习校园招聘-硬件通⽤/单板开发——第五套

华为 2024 届实习校园招聘-硬件通⽤/单板开发——第五套 部分题目分享&#xff0c;完整版带答案(有答案和解析&#xff0c;答案非官方&#xff0c;未仔细校正&#xff0c;仅供参考&#xff09;&#xff08;共十套&#xff0c;每套四十题选择题&#xff09;获取&#xff08;WX:…

Spring基础知识总结(纯文字版)

一、Spring IoC 1.1 重要概念 1&#xff09;控制反转&#xff08;Inversion of control&#xff09; 控制反转是一种通过描述&#xff08;在java中通过xml或者注解&#xff09;并通过第三方去产生或获取特定对象的方式。 控制反转IoC(Inversion of Control)是说创建对象的控…

实践部署 浦语·灵笔2 模型,写作图文并茂的文章

1 初步介绍 XComposer2 相关知识 浦语灵笔2 是基于 书生浦语2 大语言模型研发的突破性的图文多模态大模型&#xff0c;具有非凡的图文写作和图像理解能力&#xff0c;在多种应用场景表现出色&#xff0c;总结起来其具有&#xff1a; 自由指令输入的图文写作能力&#xff1a; 浦…

OAK相机如何将 YOLOv9 模型转换成 blob 格式?

编辑&#xff1a;OAK中国 首发&#xff1a;oakchina.cn 喜欢的话&#xff0c;请多多&#x1f44d;⭐️✍ 内容可能会不定期更新&#xff0c;官网内容都是最新的&#xff0c;请查看首发地址链接。 Hello&#xff0c;大家好&#xff0c;这里是OAK中国&#xff0c;我是Ashely。 专…

拿捏AVL(C++)

文章目录 前言AVL树介绍模拟实现框架查找插入验证删除完整代码 性能分析总结 前言 在本篇文章中我&#xff0c;我们将会介绍一下有关AVL树的相关内容&#xff0c;并且对一些接口进行模拟实现。 AVL树介绍 为什么会有AVL树呢&#xff1f;&#xff1f; 我们在之前学习二叉树时…

大泽动力高原柴油发电机参数型号

大泽动力高原柴油发电机是一款专为高原环境设计的柴油发电机&#xff0c;具备多项特点和优势。以下是关于大泽动力高原柴油发电机的详细介绍&#xff1a; 产品特点&#xff1a; 起动迅速&#xff1a;发电机起动时间只需几秒&#xff0c;能在短时间内达到全功率输出&#xff0c…

Go 语言中的指针

在许多现代编程语言中&#xff0c;如 Java 和 .NET&#xff0c;程序员通常无法直接控制底层的内存管理。然而&#xff0c;Go 语言提供了这样的能力&#xff0c;同时限制了可能导致错误的操作&#xff0c;比如指针运算。 文章目录 1、Go 语言中指针的介绍1.1、什么是指针&#x…

caxa新手怎么编程:一步步迈向精通的编程之旅

caxa新手怎么编程&#xff1a;一步步迈向精通的编程之旅 作为caxa的新手&#xff0c;想要快速入门并掌握编程技能&#xff0c;需要有一个系统的学习和实践过程。本文将从四个方面、五个方面、六个方面和七个方面&#xff0c;为你详细解读caxa编程的方法和技巧&#xff0c;帮助…