개발/spring

[Spring] 스프링(spring) 어노테이션(Annotation) 정리

머덕이 2022. 8. 16. 22:55

@DateTimeFormat

파라미터를 변환해서 처리해야하는 경우에 사용

public class Sample {
	
	@DateTimeFormat(pattern="yyyy/MM/dd")
	private Date date;
}

 

문자열로 yyyy/MM/dd 형식이 맞다면 자동으로 날짜 타입으로 변환


@ModelAttribute

스프링 MVC의 Controller는 기본적으로 자바 빈즈 큐칙에 맞는 객체는 다시 화면으로 객체를 전달합니다. 반면 기본 자료형의 경우는 파라미터로 선언하더라도 기본적으로 화면까지 전달되지 않습니다. 

 

@ModelAttribute 어노테이션은 강제로 전달받은 파라미터를 Model에 담아서 전달하도록 할 때 사용합니다. 타입에 관계없이 무조건 Model에 담아서 전달되므로, 파라미터로 전달된 데이터를 다시 화면에서 사용해야 할 경우에 유용하게 사용됩니다.

public class sample {

	@GetMapping("/ex01")
	String ex01(SampleVO vo, @ModelAttribute("var1") int var1) {
		return "test";
	}
}

@ControllerAdvice

코딩을 할 때 각 소스파일에 모든 예외 사항을 고려하면 처리해야하는 작업이 엄청나게 늘어날 수 밖에 없습니다. 클래스를 생성하고 @ControllerAdvice 어노테이션을 이용해 예외사항을 공통적으로 처리할 수 있습니다.

import org.springframework.http.HttpStatus;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.NoHandlerFoundException;

import lombok.extern.log4j.Log4j;

@ControllerAdvice
public class CommonException {
	
	@ExceptionHandler(Exception.class)
	public String except(Exception e, Model model) {
		model.addAttribute("exception", e);
		return "exception_page";
	}
	
	@ExceptionHandler(NoHandlerFoundException.class)
	@ResponseStatus(HttpStatus.NOT_FOUND)
	public String handle404(NoHandlerFoundException ex) {
		return "404error_page";
	}
}

@ControllerAdvice : 해당 객체가 스프링의 컨트롤러에서 발생하는 예외를 처리하는 존재임을 명시하는 용도

@ExceptionHandler : 해당 메서드가 ( ) 들어가는 예외 타입을 처리한다는 것을 의미

@ResponseStatus : HTTP 상태에 따른 예외 처리

 

* 404 에러를 @ControllerAdvice 어노테이션이 적용된 객체에서 처리하기 위해서는 web.xml 을 수정해야합니다.

→ <init-param> 태그에 throwExceptionIfNoHandlerFound 파라미터 추가

<servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
    </init-param>
    <init-param>
        <param-name>throwExceptionIfNoHandlerFound</param-name>
        <param-value>true</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>