스프링 3.0 MVC 바인딩 Enums 대소문자 구분
Spring 컨트롤러에 Request Mapping(요청 매핑)이 있는 경우...
@RequestMapping(method = RequestMethod.GET, value = "{product}")
public ModelAndView getPage(@PathVariable Product product)
그리고 제품은 열거형입니다.예를 들어 제품.집입니다
페이지 요청 시 mysite.com/home
알겠습니다.
Unable to convert value "home" from type 'java.lang.String' to type 'domain.model.product.Product'; nested exception is java.lang.IllegalArgumentException: No enum const class domain.model.product.Product.home
소문자 홈이 실제로 홈임을 enum type 컨버터가 이해하도록 하는 방법이 있습니까?
url case와 표준 대문자로 된 Java enum을 둔감하게 유지하고 싶습니다.
감사해요.
해결책
public class ProductEnumConverter extends PropertyEditorSupport
{
@Override public void setAsText(final String text) throws IllegalArgumentException
{
setValue(Product.valueOf(WordUtils.capitalizeFully(text.trim())));
}
}
등록하기
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="domain.model.product.Product" value="domain.infrastructure.ProductEnumConverter"/>
</map>
</property>
</bean>
특별한 변환이 필요한 컨트롤러에 추가
@InitBinder
public void initBinder(WebDataBinder binder)
{
binder.registerCustomEditor(Product.class, new ProductEnumConverter());
}
일반적으로 정규화를 수행하는 새 Property Editor를 생성한 다음 컨트롤러에 다음과 같이 등록합니다.
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Product.class,
new CaseInsensitivePropertyEditor());
}
Custom Property Editor를 구현해야 할 것 같습니다.
이와 같은 것:
public class ProductEditor extends PropertyEditorSupport{
@Override
public void setAsText(final String text){
setValue(Product.valueOf(text.toUpperCase()));
}
}
열거 상수에서 소문자를 사용하는 경우에 더 관대한 버전은 다음과 같습니다(아마도 그렇지 않을 수도 있지만 여전히).
@Override
public void setAsText(final String text){
Product product = null;
for(final Product candidate : Product.values()){
if(candidate.name().equalsIgnoreCase(text)){
product = candidate;
break;
}
}
setValue(product);
}
다음과 같은 모든 Enum과 함께 작동하는 일반 변환기를 만들 수도 있습니다.
public class CaseInsensitiveConverter<T extends Enum<T>> extends PropertyEditorSupport {
private final Class<T> typeParameterClass;
public CaseInsensitiveConverter(Class<T> typeParameterClass) {
super();
this.typeParameterClass = typeParameterClass;
}
@Override
public void setAsText(final String text) throws IllegalArgumentException {
String upper = text.toUpperCase(); // or something more robust
T value = T.valueOf(typeParameterClass, upper);
setValue(value);
}
}
용도:
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(MyEnum.class, new CaseInsensitiveConverter<>(MyEnum.class));
}
아니면 스카프먼이 설명하는 것처럼 전세계적으로
Spring Boot 2에서는 사용할 수 있습니다.ApplicationConversionService
. 유용한 변환기를 제공합니다. 특히org.springframework.boot.convert.StringToEnumIgnoringCaseConverterFactory
- 문자열 값을 열거 인스턴스로 변환할 책임이 있습니다.이것은 제가 발견한 가장 일반적인 솔루션(enum 당 별도의 변환기/포맷을 생성할 필요가 없음)이자 가장 간단한 솔루션입니다.
import org.springframework.boot.convert.ApplicationConversionService;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class AppWebMvcConfigurer implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
ApplicationConversionService.configure(registry);
}
}
Spring 3에 대한 질문인 것은 알고 있지만, 이것은 구글에서 검색할 때의 첫번째 결과입니다.spring mvc enums case insensitive
문구.
@GaryF의 답변에 추가하고 의견을 설명하기 위해 사용자 정의에 글로벌 사용자 정의 속성 편집기를 삽입하여 선언할 수 있습니다.AnnotationMethodHandlerAdapter
. Spring MVC는 일반적으로 이 중 하나를 기본적으로 등록하지만, 예를 들어 선택할 경우 특수하게 구성된 것을 제공할 수 있습니다.
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="webBindingInitializer">
<bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<property name="propertyEditorRegistrars">
<list>
<bean class="com.xyz.MyPropertyEditorRegistrar"/>
</list>
</property>
</bean>
</property>
</bean>
MyPropertyEditorRegistrar
의 예입니다.PropertyEditorRegistrar
, 그리고 차례로 관습을 등록합니다.PropertyEditor
봄을 머금은 물건들
이것만 선언하면 충분할 것입니다.
언급URL : https://stackoverflow.com/questions/4617099/spring-3-0-mvc-binding-enums-case-sensitive
'programing' 카테고리의 다른 글
최소 및 최대 날짜 (0) | 2023.10.12 |
---|---|
글리폰을 크게 하려면 어떻게 해야 할까요?(크기 변경?) (0) | 2023.10.12 |
Wordpress에서 Custom Field 섹션을 제거하는 방법 (0) | 2023.10.12 |
Word press Gutenberg 블록 안에서 Add on click 이벤트 (0) | 2023.10.12 |
Angular JS : ng-hide 및 ng-show API (0) | 2023.10.12 |