티스토리 뷰

스프링(Spring Framework) MVC 프로젝트를 사용하다가 문자 인코딩때문에 애를 먹고 있다면, CharacterEncodingFilter 를 사용해보길 추천한다. 이 클래스는 Spring Framework 에서 제공하는 필터용 클래스로 인자값만 정의해서 잘 쓰면 된다. web.xml 파일에 필터를 아래와 같이 정의해주면 된다.

<filter>
	<filter-name>characterEncodingFilter</filter-name>
	<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
	<init-param>
		<param-name>encoding</param-name>
		<param-value>utf-8</param-value>
	</init-param>	
	<init-param>
		<param-name>forceEncoding</param-name>
		<param-value>true</param-value>
	</init-param>
</filter>
<filter-mapping>
	<filter-name>characterEncodingFilter</filter-name>
	<url-pattern>/*</url-pattern>
</filter-mapping>

당연히 url-pattern 은 각자 프로젝트에 맞게 설정하셔야 한다.  CharacterEncodingFilter 객체에 "encoding", "forceEncoding" 두개의 값을 초기값으로 셋팅하고 있다. 인자값들을 보다보니, encoding 은 인코딩 셋팅하는 것인 건 알겠는데 forceEncoding이 무엇인지 어떤용도인지 궁금해졌다. 그래서 소스를 까봤다(?)


/**
 * Servlet 2.3/2.4 Filter that allows one to specify a character encoding for
 * requests. This is useful because current browsers typically do not set a
 * character encoding even if specified in the HTML page or form.
 *
 * <p>This filter can either apply its encoding if the request does not
 * already specify an encoding, or enforce this filter's encoding in any case
 * ("forceEncoding"="true"). In the latter case, the encoding will also be
 * applied as default response encoding on Servlet 2.4+ containers (although
 * this will usually be overridden by a full content type set in the view).
 *
 * @author Juergen Hoeller
 * @since 15.03.2004
 * @see #setEncoding
 * @see #setForceEncoding
 * @see javax.servlet.http.HttpServletRequest#setCharacterEncoding
 * @see javax.servlet.http.HttpServletResponse#setCharacterEncoding
 */
public class CharacterEncodingFilter extends OncePerRequestFilter {

	private String encoding;

	private boolean forceEncoding = false;


	/**
	 * Set the encoding to use for requests. This encoding will be passed into a
	 * {@link javax.servlet.http.HttpServletRequest#setCharacterEncoding} call.
	 * <p>Whether this encoding will override existing request encodings
	 * (and whether it will be applied as default response encoding as well)
	 * depends on the {@link #setForceEncoding "forceEncoding"} flag.
	 */
	public void setEncoding(String encoding) {
		this.encoding = encoding;
	}

	/**
	 * Set whether the configured {@link #setEncoding encoding} of this filter
	 * is supposed to override existing request and response encodings.
	 * <p>Default is "false", i.e. do not modify the encoding if
	 * {@link javax.servlet.http.HttpServletRequest#getCharacterEncoding()}
	 * returns a non-null value. Switch this to "true" to enforce the specified
	 * encoding in any case, applying it as default response encoding as well.
	 * <p>Note that the response encoding will only be set on Servlet 2.4+
	 * containers, since Servlet 2.3 did not provide a facility for setting
	 * a default response encoding.
	 */
	public void setForceEncoding(boolean forceEncoding) {
		this.forceEncoding = forceEncoding;
	}


	@Override
	protected void doFilterInternal(
			HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {

		if (this.encoding != null && 
				(this.forceEncoding || request.getCharacterEncoding() == null)) {
			request.setCharacterEncoding(this.encoding);
			if (this.forceEncoding) {
				response.setCharacterEncoding(this.encoding);
			}
		}
		filterChain.doFilter(request, response);
	}

}


doFilterInternal 메소드에 그 해답이 있다.


1. encoding 값을 안넣으면 아무것도 하지 않는다.

2. encoding 값이 입력되고 forceEncoding 가 true 이면,  HttpServletRequest, HttpServletResponse 객체 둘다에 setCharacterEncoding 메소드를 이용하여 기존값을 무시하고 입력된 encoding 값으로 강제 셋팅해준다.

3. encoding 값이 입력되고 forceEncoding 가 false 이면, HttpServletRequest 객체의 getCharacterEncoding() 값이 null 일때만 setCharacterEncoding 메소드를 이용하여 문자인코딩을 셋팅해준다. 다시말해서 forceEncoding 이 false 이면, HttpServletRequest 객체에 특정인코딩이 들어가 있으면 강제로 변환하지 않겠다는 것이다.


forceEncoding 는 입력한 인코딩으로 강제셋팅을 할것인지 말것인지에 대한 인자값이었다. 그리고 true 로 줄경우 response 객체도 셋팅을 미리 해버리게 된다. 각자 프로젝트에 맞춰 셋팅하면 될것같다. 

반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함