일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
- 워드프레스
- linkedhastset
- Login
- Thymeleaf
- mergeattributes()
- @Controller
- ChatGPT
- GA4
- HttpSession
- Polylang
- 데이터베이스
- set
- db
- @Entity
- useEffect
- 구글알고리즘
- 구글
- 플러그인
- SEO
- addallattributes()
- 인텔리제이
- 리액트오류
- JPA
- @Query
- post
- @Repository
- GET
- firebase
- 구글애널리틱스
- router
- Today
- Total
개발천재
[Spring Boot] WebMvcConfigurer 이해하기 본문
WebMvcConfigurer는 Spring MVC의 기본 설정을 변경하거나 추가할 수 있는 방법을 제공한다
WebMvcConfigurer 이해하기
WebMvcConfigurer는 Spring MVC 설정을 간편하게 커스터마이즈할 수 있도록 도와주는 인터페이스이다. 이를 통해 웹 애플리케이션에서 기본적인 MVC 설정을 변경하거나 추가할 수 있다.
예를 들면, WebMvcConfigurer는 학교의 규칙을 설정하는 교장 선생님과 비슷하다고 할 수 있다.
교장 선생님은 학교에서 학생들이 지켜야 할 규칙을 정하는 사람이다. 예를 들어, 어디서 점심을 먹을지, 어떤 과목을 선택할지, 학생들이 학교에 들어오기 전에 확인해야 할 사항 등을 설정한다. 또한 학교의 기본적인 운영은 정해져 있지만, 교장 선생님은 특정 규칙을 추가하거나 바꿀 수 있다.
스프링 애플리케이션에서 기본적인 웹 운영(요청 받기, 응답하기, 뷰 처리 등)은 이미 정해져 있다. 하지만 특정 규칙(예: 로그인 체크, 권한 검사, 정적 파일 경로 설정 등)을 변경하거나 추가하고 싶을 때 WebMvcConfigurer를 사용한다.
교장선생님으로 이해하는 WebMvcConfigurer
교장 선생님이 출석 체크 -> 인터셉터 설정
학교에 들어오는 학생들이 출석 체크를 받기 전에 어떤 규칙을 적용하는 것과 비슷하다. 예를 들어, 점심을 먹기 전에 출석을 체크할 수 있다. 이를 스프링 부트에서는 HandlerInterceptor를 사용하여 요청이 들어올 때마다 로그인 상태를 확인할 수 있다.
교장 선생님이 운동장 사용 규칙 설정 -> 정적 리소스 설정
학교에는 운동장과 같은 정해진 공간이 있다. 이 공간을 누구나 사용할 수 있는지, 특정 시간에만 사용할 수 있는지 등을 규정할 수 있다. 마찬가지로, WebMvcConfigurer에서 정적 파일(예: 이미지, CSS 파일 등)이 저장되는 경로를 지정하고, 어떻게 접근할 수 있을지 설정할 수 있다.
교장 선생님이 수업 자료를 배포하는 방법 설정 -> 뷰 설정
수업 자료를 배포하는 방법을 정하는 것도 비슷하다. 책을 나눠주는 방법(종이책, 디지털 자료 등)을 정하는 것처럼, WebMvcConfigurer는 뷰 템플릿(JSP, Thymeleaf 등)을 어떻게 처리할지 정할 수 있다.
WebMvcConfigurer 주요 설정
인터셉터 설정 (addInterceptors)
요청이 컨트롤러에 도달하기 전, 후에 실행할 인터셉터를 추가할 수 있다. 예를 들어, 로그인 체크, 권한 검사 등을 할 때 유용하다.
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns("/user/**") // 로그인 필요한 경로 설정
.excludePathPatterns("/user/login", "/user/register"); // 로그인 불필요한 경로
}
}
뷰 리졸버 설정 (configureViewResolvers)
JSP, Thymeleaf 같은 뷰 템플릿을 처리하는 방법을 설정할 수 있다.
// JSP
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.jsp("/WEB-INF/views/", ".jsp"); // JSP 뷰 위치 설정
}
}
// Thymeleaf
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.thymeleaf().prefix("classpath:/templates/") // 템플릿 위치
.suffix(".html"); // 템플릿 파일 확장자
}
}
리소스 핸들러 설정 (addResourceHandlers)
정적 파일(이미지, CSS, JavaScript 등)을 어디에서 제공할지 설정한다.
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**") // 요청 경로
.addResourceLocations("classpath:/static/"); // 정적 파일 위치
}
}
메시지 컨버터 설정 (configureMessageConverters)
JSON이나 XML 같은 데이터 형식을 객체로 변환하거나, 반대로 객체를 변환하는 방법을 설정할 수 있다.
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new MappingJackson2HttpMessageConverter()); // JSON 변환기 추가
converters.add(new MarshallingHttpMessageConverter()); // XML 변환기 추가 (필요시)
}
}
CORS 설정 (addCorsMappings)
다른 도메인에서 오는 요청을 허용하는 CORS(Cross-Origin Resource Sharing) 설정을 할 수 있다.
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**") // CORS 허용할 경로
.allowedOrigins("http://localhost:3000") // 허용할 도메인
.allowedMethods("GET", "POST", "PUT", "DELETE"); // 허용할 HTTP 메서드
}
}
WebMvcConfigurer 사용 방법
WebMvcConfigurer는 인터페이스이므로, 이를 구현하는 클래스를 만들어서 메소드 오버라이드를 통해 커스터마이징할 수 있다.
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
@Configuration // 이 클래스가 Spring의 설정 클래스임을 표시
public class WebConfig implements WebMvcConfigurer {
// 인터셉터 추가 (로그인 체크 등)
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor())
.addPathPatterns("/**") // 모든 경로에 대해 인터셉터 적용
.excludePathPatterns("/login"); // 로그인 페이지는 제외
}
// 정적 파일 처리 (예: /images, /css 등)
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**") // 정적 파일 경로
.addResourceLocations("classpath:/static/"); // 실제 파일 위치
}
// 메시지 컨버터 추가 (JSON 처리 등)
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
// JSON, XML 변환 처리 등
}
}
addInterceptors()
요청 처리 전에 또는 후에 실행할 인터셉터를 추가하는 메소드이다.
예를 들어, 로그인이나 권한 체크를 할 때 사용한다.
addResourceHandlers()
정적 리소스(예: 이미지, CSS, JavaScript 파일 등)에 대한 경로를 설정하는 메소드이다.
configureMessageConverters()
요청/응답에 대한 변환 방식(예: JSON 변환, XML 변환)을 설정하는 메소드이다.
'개발 준비 > Spring Boot' 카테고리의 다른 글
[Spring Boot] HttpSession으로 로그인 구현하기 (2) | 2025.02.20 |
---|---|
[Spring Boot] 생성일, 수정일 자동관리하기 @EnableJpaAuditing (4) | 2025.02.19 |
[Spring Boot] Validation, 검증하기 (2) | 2025.02.18 |
[Spring Boot] Bean을 정의하는 어노테이션 (1) | 2025.02.18 |
[Spring Boot] Intercepter와 HandlerInterceptor (1) | 2025.02.18 |