회사 업무/기술 도입편

[Refactoring] 국제화(Internationalization) 수정

코드몬스터 2024. 5. 10. 11:15
728x90

상황

현재 로직

  1. HTML 태그마다 data-lang 이라는 속성을 만들고 있다.
  2. data-lang의 속성 값을 자바스크립트 객체로 선언한다.
  3. 속성 값과 객체가 일치하는 값을 불러와서 국제화 처리 진행

문제점

  1. 자바 스크립트 객체로 되어있기 때문에 값들을 관리하기 어려움.(중복 등)
  2. 애플리케이션 배포가 끝나고, 이후 값을 수정하려면 엔지니어가 처리하기 어렵다.

변경 이유

  1. 스프링 프레임워크에서 이미 국제화 기능을 지원하고 있다...

다른 사이트에서 적어 놓은 글

 

However, this approach depends on the access to the application's resource files when adding a new supported language or modify the existing message files.

이 방법은 지원되는 새로운 언어를 추가하거나 기존 메시지 파일을 수정할 때 응용 프로그램의 리소스 파일에 대한 액세스에 의존한다.

 

In case an end-user is responsible for this job – this is not an optimal approach.

최종 사용자가 이 작업을 담당하는 경우 최적의 접근 방식이 아닙니다.
→ 그렇다.. 지금 업무에서도 최종적으로 개발자가 아닌 엔지니어분들이 해당 문제를 마주치게 된다.

→ 엔지니어가 수정할 수 있게 만들자.

 

Hence, we are going to explore how to move all of our localized messages to a database. This enables the end-user to add a new language or update existing localized messages at runtime.

따라서 현지화된 모든 메시지를 데이터베이스로 이동하는 방법을 살펴보려고 합니다. 이를 통해 최종 사용자는 런타임에 새로운 언어를 추가하거나 기존의 현지화된 메시지를 업데이트할 수 있다.

 


국제화 로직 시도 

인터넷 서칭

  • 일반적으로 인터넷에 찾아보면 아래와 같이 작성해서 구현하도록 되어있다.
@Configuration

public class WebConfig implements WebMvcConfigurer {

    @Bean
    public LocaleResolver localeResolver() {
        return new CookieLocaleResolver();
    }
    
    또는
    
    @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver resolver = new SessionLocaleResolver();
        resolver.setDefaultLocale(Locale.KOREAN);
        return resolver;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
        localeChangeInterceptor.setParamName("lang");
        registry.addInterceptor(localeChangeInterceptor);

    }

}

나의 생각

  • LocaleChangeInterceptor를 사용하게 되면, 모든 요청의 파라미터 값으로 lang 을 넣어줘야한다.
    • 언어 변환 요청을 처리하는 컨트롤러를 만들어 주면 되지 않을까?

 

작성 코드

    @GetMapping(value = "/admin/changeLocale.os")
    public String changeLocale(String lang, HttpServletRequest req, HttpServletResponse resp, HttpSession session) {

        // localeResolver의 locale 변경
        LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(req);
        if (localeResolver != null) {
            localeResolver.setLocale(req, resp, StringUtils.parseLocale(lang));
        }

        ... 중간 생략 ...
        
        // 요청의 이전 요청 경로로 이동
        String requestURI = req.getHeader("referer");
        if (requestURI == null) {
            requestURI = "/";
        }

        return "redirect:" + requestURI;
    }