날짜 값 변환
다음과 같이, 문자열= input을 받아서 RequestDTO의 LocalDateTime 필드에 자동으로 넣도록 하고싶다.
<input type="text" name="from" />
<input type="text" name="to" />
package spring;
import java.time.LocalDateTime;
public class MyRequestDto {
private LocalDateTime time;
public LocalDateTime getTime() {
return time;
}
public void setTime(LocalDateTime time) {
this.time = time;
}
}
이럴 때는 DTO 필드에 @DateTimeFormat(pattern = "yyyyMMddHH")
어노테이션을 붙이면 된다.
package spring;
import java.time.LocalDateTime;
public class MyRequestDto {
@DateTimeFormat(pattern = "yyyyMMddHH")
private LocalDateTime time;
public LocalDateTime getTime() {
return time;
}
public void setTime(LocalDateTime time) {
this.time = time;
}
}
PathVariable
@Controller
public class MemberController {
...
@GetMapping("/members/{id}")
public String detail(@PathVariable("id") Long memberId, Model model) {
...
}
}
Exception Handling
1 - 특정 컨트롤러 내에서
@Controller
public class MemberController {
...
@ExceptionHandler(TypeMismatchException.class)
public String handleTypeMismatchException() {
return "member/invalid";
}
@ExceptionHandler(MemberNotFoundException.class)
public String handleNotFoundException() {
return "member/noMember";
}
}
- 같은 컨트롤러에 @ExceptionHandler 어노테이션을 적용한 메서드가 존재하면 그 메서드가 Exception을 처리한다.
- 위와 같이 작성하면 MemberController 의 메서드 실행시
MemberNotFoundException 이 발생하면 handleNotFoundException() 이 실행되고, TypeMismatchException 이 발생하면 handleTypeMismatchException() 이 실행된다. - org.springframework.beans.TypeMismatchException : 경로 변수값의 타입이 올바르지 않을 때 발생
2 - 다수의 컨트롤러에 대하여
1. @ControllerAdvice & @ExceptionHandler 으로 다음과 같이 구현
package controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice("controller") // controller 패키지에 대해서
public class CommonExceptionHandler {
@ExceptionHandler(Exception.class)
public String handleRuntimeException() {
return "error/commonException";
}
}
2. 구현한 ExceptionHandler 객체를 Bean 으로 등록
package config;
import ...
@Configuration
public class ExceptionConfig {
@Bean
public CommonExceptionHandler commonExceptionHandler() {
return new CommonExceptionHandler();
}
}
@ExceptionHandler 적용 메서드 우선순위
@ControllerAdvice 클래스에 있는 @ExceptionHandler 메서드와 컨트롤러 클래스에 있는 @ExceptionHandler 메서드 중 컨트롤러에 적용된 @ExceptionHandler가 우선됨
'2021 Spring Study' 카테고리의 다른 글
Spring 21. Json request & response (0) | 2021.03.15 |
---|---|
Spring 19. 세션, 인터셉터, 쿠키 (0) | 2021.02.28 |
Spring 18. 커맨드 객체 validation (0) | 2021.02.18 |
Spring 17. 스프링 MVC 주요 기능 (0) | 2021.02.03 |
Spring 16. 서블릿 & 서블릿 컨테이너 & spring MVC (0) | 2021.01.29 |