웹 공부를 하던 중, Servlet 공부를 하면서 한글 인식에 대한 문제가 발생했다.
부스트코스 웹 프로그래밍(https://www.edwith.org/boostcourse-web/lecture/16689/)
[LECTURE] 4) Request, Response 객체 이해하기 : edwith
들어가기 전에 이번 파트를 학습하다 보면 '요청', '응답'이라는 용어가 많이 등장합니다. 이번 학습에서는 클라이언트가 서버에게 보낸 요청을 추상화한 객체 HttpServletRe... - 부스트코스
www.edwith.org
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>form</title></head>");
out.println("<body>");
String name = request.getParameter("name");
String age = request.getParameter("age");
out.println("name : " + name + "<br>");
out.println("age : " + age + "<br>");
out.println("</body>");
out.println("</html>");
}
해당 내용은 Servlet파일 부분의 내용이다.
response.setContentType("text/html; charset=utf-8");
이 부분으로는 아래와 같이 출력되지않았다. name : ???와 같이 한글깨짐현상이 계속해서 발생했다.
url부분에 ?뒤에 부분은 파라미터 값이다.
name에 input값을 한글로 넣어주는 경우 제대로 인식하지 못했다.
[해결책]
이클립스 Servers 프로젝트에 Tomcat폴더에 있는, server.xml 에서 port=8080과 port=8009 두 개의 connector에 URIEncoding="UTF-8"을 추가한다.
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" URLEncoding="UTF-8"/>
<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" URLEncoding="UTF-8"/>
부연설명)
response.setCharacterEncoding("UTF-8")
response.setContentType("text/html; charset=utf-8")
서블릿에서 화면에 데이터를 출력할때,
out.println을 사용시, 위의 코드없이 out.print("홍길동");를 한다면 '홍길동'이 출력되는 것이 아니라 ???와 같이 물음표로 출력된다.
그것을 해결하기 위한 것이 response.setCharacterEncoding("UTF-8"); 이다.
++)'홍길동'이라고 나오지 않고 '갦밟좕'과 같은 처음보는 이상한 문자가 출력이 된다. 분명 한글처리를 했는데도 이상한 문자열이 출력되는 이유는 브라우저마다 기본적으로 문자코드를 해석하는 디폴트가 다르기 때문이다.
그래서 브라우저한테 "우리는 UTF-8 방식으로 문자코드를 사용할거다. UTF-8로 사용해!!"라는 메세지를 전달해야 하는데
이런 메세지를 전달하는 것이 바로 response.setContentType("text/html; charset=utf-8"); 이다.
'웹(Web) > 백엔드(Backend)' 카테고리의 다른 글
백엔드 로드맵 (0) | 2021.01.04 |
---|---|
파이썬 구글 이미지 크롤링(uh oh! keywords is a required argument, unfortunately all 20 could not be downloaded because some images were not downloadable. 0 is all we got for this search filter!) (3) | 2020.12.16 |
Intellij Spring JDBC시작하기 (4) | 2020.06.07 |
Maven이란? CoC이란? (0) | 2020.05.31 |
(Servlet/JSP) redirect와 forward (0) | 2020.05.27 |