Spring Boot 마이그레이션 시 JSP의 JS 인코딩 깨짐 문제 해결

레거시 프로젝트를 Spring Boot 기반으로 변환하는 과정에서 인코딩 문제가 자주 발생한다. 특히, 기존 프로젝트가 GBK 인코딩을 사용하고 JSP와 JS 파일이 모두 GBK로 작성된 경우, Spring Boot의 기본 UTF-8 설정과 충돌하여 JS 영역만 깨져 보이는 현상이 나타날 수 있다.

문제 확인

JS 파일이 정상적으로 보이지 않는다면, 가장 먼저 파일 자체의 인코딩을 확인해야 한다. 프로젝트 내에서는 GBK로 저장했지만, Maven 빌드 후 target 디렉터리에 생성된 파일이 UTF-8로 변환된 경우가 많다.

예를 들어, 다음과 같은 설정으로 Maven 빌드 시 인코딩을 강제할 수 있다.

<properties>
   <project.build.sourceEncoding>GBK</project.build.sourceEncoding>
</properties>

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <configuration>
        <failOnMissingWebXml>false</failOnMissingWebXml>
        <resourceEncoding>GBK</resourceEncoding>
    </configuration>
</plugin>

여기서 maven-war-plugin 버전은 3.2.2를 사용했다. 또한, 빌드 명령에 -Dfile.encoding=GBK를 추가하면 target 파일이 GBK로 유지된다. 하지만, 이렇게 해도 브라우저에서 여전히 깨질 수 있다.

HTTP 응답 헤더 확인

문제가 지속된다면 브라우저 개발자 도구를 열어 JS 파일의 응답 헤더를 확인한다. Content-Typeapplication/javascript;charset=UTF-8로 되어 있다면, Tomcat이 파일을 UTF-8로 인코딩하여 전송한 것이다. 반면 JSP 페이지는 text/html;charset=GBK로 정상 응답된다.

이 차이를 해결하려면 서블릿 필터를 통해 JS 및 CSS 파일의 응답 인코딩을 GBK로 강제 설정해야 한다.

커스텀 필터 구현

아래와 같이 필터를 생성하여 특정 확장자(.js, .css)에 대해서만 인코딩을 GBK로 변경한다.

@WebFilter(urlPatterns = { "*.js", "*.css" }, filterName = "ResourceCharacterEncodingFilter")
public class ResourceCharacterEncodingFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String uri = req.getRequestURI().split("\\?")[0];
        
        if (!uri.endsWith(".js") && !uri.endsWith(".css")) {
            applyEncoding(req, resp, "UTF-8", chain);
            return;
        }
        applyEncoding(req, resp, "GBK", chain);
    }

    private void applyEncoding(HttpServletRequest req, HttpServletResponse resp, String charset, FilterChain chain)
            throws IOException, ServletException {
        req.setCharacterEncoding(charset);
        resp.setCharacterEncoding(charset);
        chain.doFilter(req, resp);
    }
}

이 필드는 모든 JS와 CSS 요청에 대해 인코딩을 GBK로 설정하고, 나머지 리소스는 기본 UTF-8을 유지한다.

결과

필터를 등록한 후 애플리케이션을 재시작하면 JS 파일이 정상적으로 렌더링된다. JSP 페이지의 인코딩은 그대로 GBK이며, JS도 동일하게 GBK로 응답되어 깨짐 현상이 사라진다.

태그: Spring Boot JSP 인코딩 GBK utf-8

7월 16일 00:12에 게시됨