• Home
  • About
    • lahuman photo

      lahuman

      열심히 사는 아저씨

    • Learn More
    • Facebook
    • LinkedIn
    • Github
  • Posts
    • All Posts
    • All Tags
  • Projects

Spring MVC에서 ResponsBody로 String을 전달시 한글 깨짐 현상 해결

21 Feb 2017

Reading time ~1 minute

Spring MVC 에서 ResponsBody로 String 을 전달시 한글 깨짐 현상 해결

Controller에서 단순한 문자열(String)을 ResponseBody로 전달할 경우, 깨지는 현상이 발생할 수 있습니다. 코드는 다음과 같습니다.

@RequestMapping(value="/preview/{id}", method=RequestMethod.GET)
public @ResponseBody String getContent(@PathVariable("id") long id) {
    return service.getContent(id);
}

한글이 깨지는 원인은 브라우저에서 해당 요청에 대한 응답의 헤더 값을 보면 다음과 같이 표현되어 있습니다.

Content-Type:application/json;charset=ISO-8859-1

위의 문제를 해결하기 위해서는 다음과 같이 spring servlet xml 설정을 추가해야 합니다.

<mvc:annotation-driven>
    <mvc:message-converters>
        <!-- @ResponseBody Content-Type:application/json;charset=UTF-8  -->
        <bean class="org.springframework.http.converter.StringHttpMessageConverter">
            <property name="supportedMediaTypes">
                <list>
                    <value>text/html;charset=UTF-8</value>
                </list>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

위와 같이 설정을 한 후 응답의 해더 값을 확인하면 다음과 같습니다.

Content-Type:application/json;charset=UTF-8

이후 Content 값을 확인하면, 한글이 깨지지 않고 제대로 표출되는 것을 확인할 수 있습니다.



한글Spring MVCString Share Tweet +1