Spring UTF8 한글 깨짐

오류 내용

spring 프로젝트에서 한글이 깨짐

해결 방법

1. [POST 방식] 스프링 웹 프로젝트 web.xml에 utf-8 설정

<filter> 
    <filter-name>encodingFilter</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>encodingFilter</filter-name> 
    <url-pattern>/*</url-pattern> 
 </filter-mapping> 

2. [POST 방식] .jsp 파일에 utf-8 설정

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" language="java" %>
<!-- dispatcher-servlet.xml에서의 설정 (Servlet/JSP 단에서의 설정) 예시 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
	<property name="prefix" value="/WEB-INF/views/"/>
	<property name="suffix" value=".jsp"/>
  <property name="contentType" value="text/html; charset=UTF-8"/>
</bean>
  • Servlet/JSP 단에서의 설정
    • dispatcher-servlet.xml에서의 설정은 Servlet 단에서의 설정을 의미한다.
    • .jsp 파일 상의 page 설정은 JSP 단에서의 설정을 의미한다.
  • Servlet/JSP 단에서의 설정 방법의 차이
    • JSP 디폴트 contentType: ISO-8859-1
    • 아무리 Servlet에서 response.setContentType 결정해서 보내더라도 .jsp page 자체의 contentType은 jsp spec에서 결정되므로 직접 기술해주지 않으면 ISO-8859-1로 설정된다.
    • Servlet 단에서의 설정은 JSP가 아닌 텍스트 리턴 시에만 이용된다.
  • 따라서, 직접 .jsp page에 기술하는 것이 좋다.

POST 방식에서의 한글 처리 추가 설명 (Servlet에서 한글처리)

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    // ... 생략
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /* 요청정보 Body에 있는 문자열들을 인자값으로 지정한 문자코드로 인코딩한다. */
        request.setCharacterEncoding("UTF-8");
        
        //getParameter는 중복되지 않고 유일하게 하나만 넘어올 떄 사용된다.
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        /* 응답정보 문자열들을 인자값으로 지정한 문자코드로 인코딩한다.  */
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        String htmlResponse = "<html>";
        htmlResponse += "<head><title>Query 문자열 한글 테스트</title></head>";
        htmlResponse += "<h2> your name is " + username + "<br/>";
        htmlResponse += "<h2> your password is " + password + "<br/>";

        out.println(htmlResponse);
    }
}

3. [GET 방식] Tomcat 서버의 환경 설정 파일 server.xml에 utf-8 설정

<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="UTF-8" />
<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" URIEncoding="UTF-8" />

4. .html 파일에 utf-8 설정

<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>Home</title>
</head>

관련된 Post

References