헤르메스 LIFE

[Spring] 개발환경 구축 - MessagesSource 본문

Spring Framework

[Spring] 개발환경 구축 - MessagesSource

헤르메스의날개 2022. 12. 22. 01:18
728x90

SimpleSpring4.zip
0.02MB

Spring 개발환경을 갑자기 구축하려고 하다보니, 막막합니다.

하나 하나 구축해 보겠습니다


개발환경

Spring 4.3.30.RELEASE

MAVEN 3.8.4

Logback 1.2.9


DispatcherServlet.xml

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <mvc:annotation-driven />

    <!-- 빈 설정을 어노테이션 기반으로 하겠다는 설정태그 -->
    <context:component-scan base-package="simple">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan>

    <!-- CSS, JS, 이미지 등의 자원은 거의 변하지 않기 때문에, 웹 브라우저에 캐시를 하면
         네트워크 사용량, 서버 사용량, 웹 브라우저의 반응 속도 등을 개선할 수 있다. -->
    <mvc:resources mapping="/static/**" location="/static/" />
    <mvc:resources location="/resources/**" mapping="/resources/"></mvc:resources>
    
    
    <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <!-- Encoding 설정 -->
        <property name="defaultEncoding" value="UTF-8"/> 
        <!-- Reload Cache 설정 -->
        <property name="cacheSeconds" value="5"/>
        <!-- basenames 설정: 아래처럼 하면 WEB-INF 밑의 message 폴더 아래의 labels로 시작하는 모든 Property-->
        <property name="basenames">
            <list>
                <value>/WEB-INF/messages/message</value>
                <value>classpath:/messages/message</value>
            </list>
        </property>       
    </bean>
     
    <!-- MessageSource를 사용하기 위한 Accessor 설정 -->
    <bean id="messageSourceAccessor" class="org.springframework.context.support.MessageSourceAccessor">
        <constructor-arg ref="messageSource"/>
    </bean>

    <!-- Default Location 설정 -->
    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
        <property name="defaultLocale" value="ko"></property>
    </bean>
    
    <!--
     mvc:default-servlet-handler
     요청 경로와 일치하는 컨트롤러를 찾는다.
     컨트롤러가 존재하지 않으면, 디폴트 서블릿 핸들러에 전달한다.
     DispatcherSerlvet이 처리하지 못한 요청을 DefaultSerlvet에게 넘겨주는 역할을 하는 핸들러
     *.css와 같은 컨트롤러에 매핑되어 있지 않은 URL 요청은 최종적으로 Default Servlet에 전달되어 처리하는 역할
     
     
     web.xml 파일의 dispatcher 가 / 의 경우 설정한다.
     <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    -->
    <mvc:default-servlet-handler />

    <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

HelloController.java

package simple.spring.basic;

import java.util.Locale;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class HelloController {

    private static Logger logger = LoggerFactory.getLogger(HelloController.class);

    @Autowired
    private MessageSource messageSource;

    @RequestMapping(value = { "/", "/welcome" }, method = RequestMethod.GET)
    public String getHomePage( ModelMap model ) {
        logger.info("[HelloController.getHomePage] 여기가 실행될까..?");
        return "index";
    }

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String hello( Map<String, Object> model ) {
        logger.info("[HelloController.hello] Hello World");

        logger.info("Message :: {}", messageSource.getMessage("mesage01", null, "default message", Locale.KOREA)); // 안녕하세요 출력
        logger.info("Message :: {}", messageSource.getMessage("mesage02", new String[] {"홍길동"}, "default message", Locale.US));    // hi 출력
        logger.info("Message :: {}", messageSource.getMessage("mesage03", null, "default message", Locale.KOREA)); // 안녕하세요 출력
        logger.info("Message :: {}", messageSource.getMessage("mesage04", new String[] {"홍길동"}, "default message", Locale.US));    // hi 출력
        
        model.put("name", "Spring4 MVC");
        model.put("msg", "Hello World");

        return "hello";
    }
}

결과


https://hermeslog.tistory.com/648

 

[Spring] 개발환경 구축 - Logback

Spring 개발환경을 갑자기 구축하려고 하다보니, 막막합니다. 하나 하나 구축해 보겠습니다 개발환경 Spring 4.3.30.RELEASE MAVEN 3.8.4 Logback 1.2.9 pom.xml 4.0.0 SimpleSpring4 SimpleSpring4 0.0.1-SNAPSHOT war SimpleSpring4

hermeslog.tistory.com

 

728x90