4차산업혁명의 일꾼/웹개발

스프링부트에서 React 연결

르무엘 2024. 12. 26. 04:33

@Slf4j
@Configuration
public class WebConfiguration implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 리소스 핸들러를 등록 ( ReactResourceResolver)
        ResourceResolver resolver = new ReactResourceResolver();
        registry.addResourceHandler("/**")
                .resourceChain(true)
                .addResolver(resolver);
    }

    public class ReactResourceResolver implements ResourceResolver {
        // react 리소스 위치
        private static final String REACT_DIR = "/static/";
        // 정적 리소스 이름
        private static final String REACT_STATIC_DIR = "static";
        // 정적 리소스의 확장자를 정의
        private Resource index = new ClassPathResource(REACT_DIR + "index.html");
        private List<String> staticExtension = Arrays.asList("png", "jpg", "io", "json", "js", "html");

        // 요청경로로 보내거나 없으면 index로 보낸다.
        private Resource resolve(String requestPath) {
            log.info(requestPath);
            if (requestPath == null) {
                return null;
            }
            if (staticExtension.contains(requestPath)
                    || requestPath.startsWith(REACT_STATIC_DIR)) {
                return new ClassPathResource(REACT_DIR + requestPath);
            } else {
                return index;
            }
        }

        @Override
        public Resource resolveResource(HttpServletRequest request, String requestPath, List<? extends Resource> locations, ResourceResolverChain chain) {
            return resolve(requestPath);
        }

        @Override
        public String resolveUrlPath(String resourcePath, List<? extends Resource> locations, ResourceResolverChain chain) {
            Resource resolvedResource = resolve(resourcePath);
            if (resolvedResource == null) {
                return null;
            }
            try {
                return resolvedResource.getURL().toString();
            } catch (IOException e) {
                return resolvedResource.getFilename();
            }
        }
    }
}
LIST