SPRING BOOT

[SPRING BOOT] 다국어 프로젝트 만들기

민덕이 2019. 11. 25. 15:50
반응형

이번 포스팅에서는 스프링 부트로 다국어 프로젝트를 만들려고 한다.

한국어, 영어, 일본어를 사용하려고 한다.

 

demo.zip
0.08MB


프로젝트 전체 경로

 

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.1.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<!-- JSTL tag lib -->
		<dependency>
			<groupId>javax.servlet.jsp.jstl</groupId>
			<artifactId>javax.servlet.jsp.jstl-api</artifactId>
			<version>1.2.1</version>
		</dependency>

		<dependency>
			<groupId>taglibs</groupId>
			<artifactId>standard</artifactId>
			<version>1.1.2</version>
		</dependency>

		<!-- Tomcat for JSP rendering -->
		<dependency>
			<groupId>org.apache.tomcat.embed</groupId>
			<artifactId>tomcat-embed-jasper</artifactId>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>

		<!-- log4jdbc -->
		<dependency>
			<groupId>org.bgee.log4jdbc-log4j2</groupId>
			<artifactId>log4jdbc-log4j2-jdbc4.1</artifactId>
			<version>1.16</version>
		</dependency>

		<!-- exclude logback , add log4j2 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
			<exclusions>
				<exclusion>
					<groupId>org.springframework.boot</groupId>
					<artifactId>spring-boot-starter-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-log4j2</artifactId>
		</dependency>

		<dependency>
			<groupId>net.rakugakibox.util</groupId>
			<artifactId>yaml-resource-bundle</artifactId>
			<version>1.1</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
	<packaging>war</packaging>
</project>

 

 

application.yml

server:
  port: 80

spring:
  profiles:
    active: local_server
  
  task:
    execution:
      pool:
        core-size: 8
        max-size: 8
  
  servlet:
    multipart:
      max-file-size: 500MB
      max-request-size: 500MB
---
      
spring:
  profiles: local_server
  messages:
    basename: messages/message
    encoding: UTF-8
  devtools:
    livereload:
      enabled: true
  mvc:
    view:
      prefix: /WEB-INF/jsp/
      suffix: .jsp
      
# ===============================
# = tomcat ajp Property
# ===============================
tomcat:
  ajp:
    protocol: AJP/1.3
    port: 8509  

logging:
  config: classpath:log4j2.xml

 

 

그 다음 resource 폴더 아래 messages를 생성 후 message.yml, messages_ko.yml, messages_en.yml, messages_jp.yml 파일을 만든다.

 

message.yml, message_ko.yml

demo:
   ko: 한국어[한]
   en: 영어[한]
   jp: 일본어[한]

 

messages_en.yml

demo:
   ko: 한국어[영]
   en: 영어[영]
   jp: 일본어[영]

 

messages_jp.yml

demo:
   ko: 한국어[일]
   en: 영어[일]
   jp: 일본어[일]

 

 

그다음 com.example.demo.config 패키지 생성 후 MessageSourceConfig.java 파일을 만든다.

package com.example.demo.config;

import net.rakugakibox.util.YamlResourceBundle;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

@Configuration
public class MessageSourceConfig extends WebMvcConfigurerAdapter {

     @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver slr = new SessionLocaleResolver();
        slr.setDefaultLocale(Locale.KOREA);
        return slr;
    }

    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
        lci.setParamName("lang");
        return lci;
    }
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(localeChangeInterceptor());
    }
    
    @Bean("messageSource")
    public MessageSource messageSource(
            @Value("${spring.messages.basename}") String basename,
            @Value("${spring.messages.encoding}") String encoding
    ) 
    {
        YamlMessageSource ms = new YamlMessageSource();
        ms.setBasename(basename);
        ms.setDefaultEncoding(encoding);
        ms.setAlwaysUseMessageFormat(true);
        ms.setUseCodeAsDefaultMessage(true);
        ms.setFallbackToSystemLocale(true);
        return ms;
    }
}

class YamlMessageSource extends ResourceBundleMessageSource {
    @Override
    protected ResourceBundle doGetBundle(String basename, Locale locale) throws MissingResourceException {
        return ResourceBundle.getBundle(basename, locale, YamlResourceBundle.Control.INSTANCE);
    }
}

 

 

com.example.demo.controller 패키지 생성 후 DemoController.java 파일을 만든다.

package com.example.demo.controller;

import java.util.Locale;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;


@RestController
public class DemoController {
    private static final Logger log = LogManager.getLogger(DemoController.class);
    
	@RequestMapping(value="/demo.do")
    public ModelAndView demo(Locale locale) throws Exception{
    	ModelAndView mv = new ModelAndView("demo/demo");	
    	String lang = locale.getLanguage();

    	log.debug("lang==" + lang);
    	mv.addObject("lang", lang);
    	return mv;
    }
}

 

 

마지막으로 demo.jsp를 만든다.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UFT-8">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script>
$(function(){
	$('select').on('change', function(){
	    location.href = "/demo.do?lang=" + $(this).val();
	});
})
</script>
</head>
<body>
	<select>
		<option value="ko"<c:if test="${lang eq 'ko'}"> selected</c:if>><spring:message code="demo.ko" text="default text" /></option>
		<option value="en"<c:if test="${lang eq 'en'}"> selected</c:if>><spring:message code="demo.en" text="default text" /></option>
		<option value="jp"<c:if test="${lang eq 'jp'}"> selected</c:if>><spring:message code="demo.jp" text="default text" /></option>
	</select>
	
</body>
</html>

 

 

이제 톰캣을 실행 후 localhost/demo.do 에서 확인해보자!

한국어

 

영어

일본어

반응형