공부/Spring

[Spring] ControllerAdvice

Dr.thousand 2022. 9. 27. 11:11
728x90

금액같은경우 Long 타입으로 정의하는데 이걸 프론트에서 일일히 컴마를 제거하기에는 불편함을 느꼈다.

그래서 파라미터를 서버로 전달해서 파싱하는 과정에서 컴마를 제거하는 과정을 넣으려고했다.

 

@ControllerAdvice(annotations = {RestController.class})
public class CustomControllerAdvice {
    @InitBinder
    public void initBinder(WebDataBinder dataBinder) {
        dataBinder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
        dataBinder.registerCustomEditor(Long.class, new LongPropertyEditor());
    }
}

 

일단은 이렇게해서 RestController 어노테이션이 있는 컨트롤러는 빈값을 Null처리 하는것과 LongPropertyEditor에서 컴마를 제거하는 에디터를 완성했다.

 

public class LongPropertyEditor extends PropertyEditorSupport{


    @Override
    public String getAsText() {
        // TODO Auto-generated method stub
        Object value = getValue();

        System.out.println("VALUE !!! : " + value);
        return (value != null ? value.toString() : "");
    }

    @Override
    public void setAsText(String text) throws IllegalArgumentException {

        System.out.println("TEXT :" + text);
        if(StringUtils.isEmpty(text)) {
            setValue(null);
        }else {
            text = text.replaceAll(",", "");
        }
        setValue(text);
    }
}

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/ControllerAdvice.html

 

ControllerAdvice (Spring Framework 5.3.23 API)

Specialization of @Component for classes that declare @ExceptionHandler, @InitBinder, or @ModelAttribute methods to be shared across multiple @Controller classes. Classes annotated with @ControllerAdvice can be declared explicitly as Spring beans or auto-d

docs.spring.io

728x90
반응형

'공부 > Spring' 카테고리의 다른 글

[QueryDSL] QueuryDSL vs JPQL  (0) 2023.12.18
[스프링] AuditorAware  (1) 2023.11.22
[스프링]Spring Security - SecurityFilterChain  (0) 2023.11.22
BeanFatory와 ApplicationContext  (0) 2022.03.06
스프링 IoC , DI  (0) 2022.03.03