素材巴巴 > 程序开发 >

请求参数转换为枚举类型

程序开发 2023-09-05 15:51:02

在之前我们写了一篇 实体类通过配置实现实体类枚举类型的转换,提高了代码的可读性 链接地址

今天我想要把请求的参数,转换为枚举类型,如下图案例代码所示

/*** @author F* curl example:* 	curl -X GET localhost:9999/type?type=1*/
 @RestController
 public class EnumConvertController {@GetMapping("/type")public String type(@RequestParam("type") TypeEnum typeEnum) {return typeEnum.name();}@GetMapping("/{type}")public String typeByPathVariable(@PathVariable("type") TypeEnum typeEnum) {return typeEnum.name();}@PostMapping("/status")public String status(@RequestParam("status") StatusEnum statusEnum) {return statusEnum.toString();}
 }
 

首先我们先提供一个基础父枚举

public interface BaseEnum {int code();
 }
 

然后实现一个类型枚举 TypeEnum

import com.fasterxml.jackson.annotation.JsonValue;public enum TypeEnum implements BaseEnum {COOL(0),HOT(1),;private int code;TypeEnum(int code) {this.code = code;}@Overridepublic int code() {return code;}
 }
 

配置一个转换工具类

@Component
 public class RequestFieldToEnumConvert implements Converter {private Map enumMap = new HashMap<>();public  RequestFieldToEnumConvert() {}public RequestFieldToEnumConvert(Class enumType) {T[] enums = enumType.getEnumConstants();for (T e : enums) {enumMap.put(String.valueOf(e.code()), e);}}@Overridepublic T convert(String source) {T t = enumMap.get(source);if (t == null) {throw new RuntimeException("枚举类型不存在");}return t;}
 }
 

配置请求字段枚举转换工厂

@Component
 public class RequestFieldToEnumConvertFactory implements ConverterFactory {private static final Map, Converter> CONVERTERS = new HashMap<>();@Overridepublic  Converter getConverter(Class targetType) {Converter converter = CONVERTERS.get(targetType);if (converter == null) {converter = new RequestFieldToEnumConvert<>(targetType);CONVERTERS.put(targetType, converter);}return converter;}
 }
 

然后我们需要把转换工厂配置到MVC配置中,作为转换配置

@Configuration
 public class WebMvcConfig implements WebMvcConfigurer {private final RequestFieldToEnumConvertFactory enumConvertFactory;public WebMvcConfig(RequestFieldToEnumConvertFactory enumConvertFactory) {this.enumConvertFactory = enumConvertFactory;}@Overridepublic void addFormatters(FormatterRegistry registry) {registry.addConverterFactory(enumConvertFactory);}
 }
 

现在让我们来看看成果

video


标签:

素材巴巴 Copyright © 2013-2021 http://www.sucaibaba.com/. Some Rights Reserved. 备案号:备案中。