Spring

Spring framework 프로젝트 설정 part2. Spring 구성(with Java)

RE.YEOL 2023. 4. 24. 20:41
💡 환경
     PC: MacBoock Pro (16-inch, 2021)
     OS: macOS Ventura Version 13.3.1
     CPU: Apple M1 Pro
     Memory: 16GB
💡 프로젝트 환경
    Spring framework 6.0.8

Spring 구성

Servlet 3.0 부터는 web.xml ServletContainerInitializer를 구현하여 web.xml에서 서블릿 컨텍스트 초기화 하였던 부분을 Java에서 설정해보도록 하겠습니다.

서블릿 컨텍스트 초기화
web.xml에서 했던 서블릿 등록/매핑, 리스너 등록, 필터 등록 같은 작업등을 말합니다.

gradle에 추가한 spring-webmvc 라이브러리에 ServletContainerInitializer를 구현한 클래스가 포함되어 있고 WebApplicationInitializer인터페이스를 구현 클래스를 찾아 초기화 작업 역할을 수행합니다.

 

Spring 구성을 위해 기본 패키지(org.example) 하위에 config패키지를 생성합니다.

WebApplicationInitializer 인터페이스 구현

WebInit 을 아래와 같이 작성하였습니다.

import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

public class WebInit implements WebApplicationInitializer {


    @Override
    public void onStartup(ServletContext servletContext) {

        //Spring Framework 프로젝트 설정을 위한 클래스의 객체생성
        AnnotationConfigWebApplicationContext webApplicationContext = new AnnotationConfigWebApplicationContext();
        webApplicationContext.register(WebMvcConfig.class);

        //요청 발생 시 처리를 DispatcherServlet으로 설정
        DispatcherServlet dispatcherServlet = new DispatcherServlet(webApplicationContext);
        ServletRegistration.Dynamic appServlet = servletContext.addServlet("dispatcherServlet", dispatcherServlet);

        //부가설정
        appServlet.setLoadOnStartup(1);
        appServlet.addMapping("/");

        // 인코딩 설정
        FilterRegistration.Dynamic filter = servletContext.addFilter("encodingFilter", CharacterEncodingFilter.class);
        filter.setInitParameter("encoding", StandardCharsets.UTF_8.name());

        //dispatcher에 의해서 편집한 경로 UTF-8로 세팅
        filter.addMappingForServletNames(null, false, "dispatcher");

    }

}

 

WebMvcConfig

package org.example.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebMvc
@ComponentScan("org.example")
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        // Controller 메소드가 view name을 반환 시 view name 앞에 경로, 뒤에 확장자를 붙여주도록 설정한다.
        WebMvcConfigurer.super.configureViewResolvers(registry);
        registry.jsp("/WEB-INF/views/", ".jsp");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //정적 파일 경로 매핑
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }
}