서블릿_한글 꺠짐 인코딩 (post, get방식)
2018. 12. 5. 10:07ㆍServer/Servlet
Servlet_한글 데이터 인코딩하는 방법
get방식이든 post방식이든 인코딩을 따로 해주지 않으면 client에게서 한글 데이터를 받았을 경우 깨질 수 있다.
- get 방식 : input type이 password인 경우 무조건 영어로 받는다. (한글을 영어로 바꿈)
- post : input type이 text인 경우 깨져서 받고
input type이 password인 경우 한글이 영어로 바뀌어서 받아진다.
따라서 이 문제를 해결하기 위해서는
아래와 같이 간단한 코드를 추가해주면 된다.
// request 문자셋 변경
// [중요] request.getParameter()보다 먼저 기술해야 한다.
request.setCharacterEncoding("UTF-8");
// response 문자셋 변경
response.setContentType("text/html; charset = utf-8");
ex)
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 31 32 33 34 35 36 37 38 39 40 41 | public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ //System.out.println("오니 ?"); // 한글 깨지는 경우 /*String userId = request.getParameter("userId"); String password = request.getParameter("password"); System.out.println("ID : " + userId); System.out.println("PASSWORD : " + password);*/ // 한글 깨짐 방지 // 1. 전송값에 한글이 있을 경우 처리할 수 있도록 인코딩 처리를 함 // 반드시 값 꺼내오기 전에 해야 한다. request.setCharacterEncoding("utf-8"); // 예외처리 throws UnsupportedEncodingException response.setContentType("text/html; charset=UTF-8"); // 2. view에서 보낸 전송값을 꺼내서 변수에 저장하기 String userId = request.getParameter("userId"); String password = request.getParameter("password"); System.out.println("ID : " + userId); System.out.println("PASSWORD : " + password); // 3. 웹 페이지에 스트림 연결 PrintWriter out = response.getWriter(); // 4. 스트림을 통해 출력 out.println("<html><head></head>"); out.println("<body>"); out.println("ID : " + userId + "<br>"); out.println("PASSWORD : " + password); out.println("</body></html>"); out.close(); } | cs |
'Server > Servlet' 카테고리의 다른 글
서블릿_Servlet (0) | 2018.12.04 |
---|