Spring ‐ 스프링 MVC 구조 이해 - dnwls16071/Backend_Study_TIL GitHub Wiki
요청 처리 순서 : HTTP 요청 - 필터 - 인터셉터 - 서블릿(디스패처 서블릿) - 핸들러(컨트롤러) - HTTP 응답
- 핸들러 조회 : 핸들러 매핑을 통해 요청 URL에 매핑된 핸들러를 조회한다.
- 핸들러 어댑터 조회 : 핸들러를 실행할 수 있는 핸들러 어댑터를 조회한다.
- 핸들러 어댑터 실행 : 핸들러 어댑터를 실행한다.
- 핸들러 실행 : 핸들러 어댑터가 실제 핸들러를 실행한다.
- ModelAndView 반환 : 핸들러 어댑터는 핸들러가 반환하는 정보를 ModelAndView로 변환해서 반환한다.
- ViewResolver 호출 : 뷰 리졸버를 찾아서 실행한다.
- View 반환 : 뷰 리졸버는 논리 이름을 물리 이름으로 바꾸고 렌더링 역할을 하는 뷰 객체를 반환한다.
- 뷰 렌더링 : 뷰를 통해서 뷰를 렌더링한다.
- 상속 다이어그램을 보면 디스패처 서블릿도 결국 HttpServlet을 상속받고 있다.
❗로그 사용시 장점
- 쓰레드 정보, 클래스 이름 등과 같은 부가 정보를 함께 볼 수 있고 출력 모양을 조정할 수 있다.
- 로그 레벨에 따라 개발 서버에서는 모든 로그를 출력하고 운영서버에서는 출력하지 않는 등 로그를 상황에 맞게 조절할 수 있다.
- 시스템 아웃 콘솔에만 출력하는 것이 아니라 파일이나 네트워크 등 로그를 별도의 위치에 남길 수 있다. 특히 파일로 남길 때는 일별, 특정 용량에 따라 로그를 분할하는 것도 가능하다.
- 성능도 일반 System.out보다 좋다. 실무에서는 꼭 로그를 사용하는 것을 권장한다.
- @RestController vs @Controller
- @RestController의 경우 : 반환 값으로 뷰를 찾는 것이 아니라 HTTP 메시지 바디에 바로 입력한다.
- @Controller의 경우 : 반환 값이 String이면 뷰를 찾아 뷰가 렌더링된다.
- @ResponseBody를 사용
- HTTP BODY에 문자 내용을 직접 반환한다.
- 뷰 리졸버 대신에 HttpMessageConverter가 동작한다.
- 기본 문자 처리 : StringHttpMessageConverter
- 기본 객체 처리 : MappingJackson2HttpMessageConverter
public interface HttpMessageConverter<T> {
/**
* Indicates whether the given class can be read by this converter.
* @param clazz the class to test for readability
* @param mediaType the media type to read (can be {@code null} if not specified);
* typically the value of a {@code Content-Type} header.
* @return {@code true} if readable; {@code false} otherwise
*/
boolean canRead(Class<?> clazz, @Nullable MediaType mediaType);
/**
* Indicates whether the given class can be written by this converter.
* @param clazz the class to test for writability
* @param mediaType the media type to write (can be {@code null} if not specified);
* typically the value of an {@code Accept} header.
* @return {@code true} if writable; {@code false} otherwise
*/
boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType);
/**
* Return the list of media types supported by this converter. The list may
* not apply to every possible target element type and calls to this method
* should typically be guarded via {@link #canWrite(Class, MediaType)
* canWrite(clazz, null}. The list may also exclude MIME types supported
* only for a specific class. Alternatively, use
* {@link #getSupportedMediaTypes(Class)} for a more precise list.
* @return the list of supported media types
*/
List<MediaType> getSupportedMediaTypes();
/**
* Return the list of media types supported by this converter for the given
* class. The list may differ from {@link #getSupportedMediaTypes()} if the
* converter does not support the given Class or if it supports it only for
* a subset of media types.
* @param clazz the type of class to check
* @return the list of media types supported for the given class
* @since 5.3.4
*/
default List<MediaType> getSupportedMediaTypes(Class<?> clazz) {
return (canRead(clazz, null) || canWrite(clazz, null) ?
getSupportedMediaTypes() : Collections.emptyList());
}
/**
* Read an object of the given type from the given input message, and returns it.
* @param clazz the type of object to return. This type must have previously been passed to the
* {@link #canRead canRead} method of this interface, which must have returned {@code true}.
* @param inputMessage the HTTP input message to read from
* @return the converted object
* @throws IOException in case of I/O errors
* @throws HttpMessageNotReadableException in case of conversion errors
*/
T read(Class<? extends T> clazz, HttpInputMessage inputMessage)
throws IOException, HttpMessageNotReadableException;
/**
* Write a given object to the given output message.
* @param t the object to write to the output message. The type of this object must have previously been
* passed to the {@link #canWrite canWrite} method of this interface, which must have returned {@code true}.
* @param contentType the content type to use when writing. May be {@code null} to indicate that the
* default content type of the converter must be used. If not {@code null}, this media type must have
* previously been passed to the {@link #canWrite canWrite} method of this interface, which must have
* returned {@code true}.
* @param outputMessage the message to write to
* @throws IOException in case of I/O errors
* @throws HttpMessageNotWritableException in case of conversion errors
*/
void write(T t, @Nullable MediaType contentType, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException;
}
- HttpMessageConverter 인터페이스는 HTTP 요청, HTTP 응답 둘 다 사용된다.
-
canRead()
,canWrite()
: 메시지 컨버터가 해당 클래스, 해당 미디어 타입을 지원하는가? -
read()
,write()
: 메시지 컨버터를 통해서 메시지를 읽고 쓰는 기능
-
- 우리가 편하게 사용하는 @RequestMapping, @RequiredArgsConstructor 등의 어노테이션을 편하게 사용할 수 있는 이유는 바로 ArgumentResolver에 있다.
- 어노테이션 기반 컨트롤러를 처리하는 RequestMappingHandlerAdapter는 ArgumentResolver를 호출해서 컨트롤러가 필요로 하는 다양한 파라미터의 값을 생성한다. 그리고 이렇게 파라미터 값이 모두 준비되어 컨트롤러를 호출한 후 결과값을 넘겨준다.
- 적용 사례 - JWT 토큰 기반 인증 방식에서 현재 유저를 식별할 수 있도록 하는 어노테이션 개발 경험