본문 바로가기
SpringBoot/(책)스프링부트 시작하기

[springboot] 10. 한글처리를 위한 인코딩 설정하기

by 평범한kiki 2023. 4. 26.

* 한글처리를 위한 인코딩 설정하기
- 스프링 부트 2.1.x 버전에는 이미 인코딩 필터가 적용되어 있어 해당버전 아래버전이나 다른 인코딩 필터를 추가할 경우 사용한다

 

/board/src/main/java/board/configuration/WebMvcConfiguration.java
CharacterEncodingFilter 스프링이 제공하는 클래스로 웹에서 주고받는 데이터의 헤더값을 UTF-8로 인코딩해준다
HttpMessageConverter @ResponseBody 이용하여 결과 출력시 

package board.configuration;

import java.nio.charset.Charset;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import board.interceptor.LoggerInterceptor;

//@EnableWebMvc
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer{

	//인터셉터 등록 addPathPatterns():요청주소의 패턴/excludePathPatterns():제외 주소의 패턴
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(new LoggerInterceptor())
		        .order(1)
		        .addPathPatterns("/**")
		        .excludePathPatterns("/css/**","/error", "/error/**"); // 위처럼 인터셉터는 등록시 중복 호출이 일어나지 않도록 URL 패턴을 지정해주면 된다.
	}
	
  	
   @Bean 
    public Filter characterEncodingFilter() { 
	  CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
	  characterEncodingFilter.setEncoding("UTF-8");
	  characterEncodingFilter.setForceEncoding(true); return
	  characterEncodingFilter(); 
    }
  
    @Bean 
    public HttpMessageConverter<String> responseBodyConverter(){ 
	  return new StringHttpMessageConverter(Charset.forName("UTF-8")); 
    }
 	 
}