Spring/Spring MVC

[Spring MVC] 4-2. Handler Methods: Type Conversion

noahkim_ 2023. 10. 17. 01:16

1. Type Conversion

항목 설명
문자열 변환 (기본 방식)
@RequestParam, @PathVariable, @RequestHeader 등은 기본적으로 문자열 처리
문자열이 아닌 변환
인자가 String이 아닌 경우, 등록된 Converter, Formatter를 통해 자동 타입 변환 수행

 

예제) 문자열 변환

더보기

1. 기본 제공 구현체

@GetMapping("/user")
public String get(@RequestParam("newName") String newName, Model model) {
    model.addAttribute("message", "다음번에 갱신할 이름: " + newName);
    return "home";
}

 

2. 커스터마이징

public class StringToUserRequestConverter implements Converter<String, UserRequest> {

    @Override
    public UserRequest convert(String sUsername) {
        return new UserRequest(sUsername);
    }
}
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new StringToUserRequestConverter());
    }
}

 

@GetMapping(value = "/test/user", produces = "text/plain;charset=UTF-8")
@ResponseBody
public String getUser(@RequestParam("username") UserRequest userRequest) {
    return "유저 이름: " + userRequest.getUsername();
}

 

예제) 문자열이 아닌 변환

더보기
@GetMapping(value = "/user/visit/{visitDate}", produces = "text/plain;charset=UTF-8")
@ResponseBody
public String getVisitDate(@PathVariable LocalDate visitDate) {
    return "방문 년: " + visitDate.getYear();
}
GET http://localhost:8080/user/visit/2024-04-11

 

2. Convertion Types

항목 설명
Customizing Type Conversion
- WebDataBinder를 통해 커스텀 컨버터 등록
- 또는 FormattingConversionService에 Converter, Formatter 등록
Empty String Value
빈 문자열("")은 null로 처리됨
nullable
- @RequestParam(required = false)로 명시
- @Nullable 어노테이션 사용
Non-null
Spring 5.3부터는 타입 변환 후에도 null이 자동 검증됨
→ MissingRequestValueException 등 발생 가능

 

예제) Customizing Type Conversion

더보기
public class LocalDateFormatter implements Formatter<LocalDate> {

    private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");

    @Override
    public LocalDate parse(String text, Locale locale) throws ParseException {
        return LocalDate.parse(text, formatter);
    }

    @Override
    public String print(LocalDate object, Locale locale) {
        return object.format(formatter);
    }
}
@Controller
public class HomeController {

    private MemberRepository memberRepository;
    private ApplicationContext applicationContext;

    public HomeController(MemberRepository memberRepository, ApplicationContext applicationContext) {
        this.memberRepository = memberRepository;
        this.applicationContext = applicationContext;
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.addCustomFormatter(new LocalDateFormatter());
    }

    @GetMapping("/date")
    @ResponseBody
    public String getDate(@RequestParam LocalDate date) {
        return "날짜: " + date;
    }
}

 

기능 설명
@InitBinder 컨트롤러가 요청을 처리하기 전에 자동으로 호출되는 메서드
같은 클래스 내의 모든 핸들러 메서드에 적용됨
WebDataBinder를 설정할 수 있음
WebDataBinder Spring MVC에서 HTTP 요청 파라미터를 자바 객체로 바인딩할 때 사용하는 도구

 

GET http://localhost:8080/date?date=2025/04/12
  • 출력) 날짜: 2025-04-12

 

예제) Empty String Value

더보기
@GetMapping(value ="/empty", produces = "text/plain;charset=UTF-8")
@ResponseBody
public String emptyString(@RequestParam(required = false) String name) {
    return Objects.isNull(name) ? "이름 없음" : "이름: " + name;
}

 

예제) nullable

더보기
@GetMapping(value ="/nullable", produces = "text/plain;charset=UTF-8")
@ResponseBody
public String nullable1(@RequestParam @Nullable String hobby) {
    return Objects.isNull(hobby) ? "취미 없음" : "이름: " + hobby;
}

 

예제) Non-null

더보기
@GetMapping(value ="/non-null", produces = "text/plain;charset=UTF-8")
@ResponseBody
public String nonNull(@RequestParam String mustExist) {
    return "값: " + mustExist;
}
  • /non-null 호출 시 → 400 Bad Request
  • 메시지: Required request parameter 'mustExist' for method parameter type String is not present

 

3. Handling Missing Values

  • 누락된 값이나 변환 후의 값이 null이면 예외가 발생합니다.

 

Missing...Exception

  • 누락된 값이나 변환 후의 null 값에 대한 예외입니다.
  • MissingRequestValueException 클래스를 상속합니다.
예외 클래스 발생 상황 설명
MissingPathVariableException
@PathVariable로 지정한 URL 경로 변수가 누락된 경우
MissingRequestHeaderException
@RequestHeader로 지정한 HTTP 헤더가 누락된 경우
MissingServletRequestParameterException
@RequestParam 또는 쿼리 파라미터가 필수인데 누락된 경우
MissingRequestCookieException
@CookieValue로 지정한 쿠키가 누락된 경우 (Spring 5.3 이상)
MissingMatrixVariableException
@MatrixVariable로 지정한 매트릭스 변수(matrix variable)가 누락된 경우

 

 

출처