[JSP] JSP에서 쿠키(Cookie)에 한글 저장시 에러 해결하는 방법
- JSP 에서 쿠키에 한글 저장시 아래와 같은 에러가 나타날 수 있습니다.
java.lang.IllegalArgumentException: Control character in cookie value or attribute.
- 해결방법은 쿠키 생성시 URLEncoder.encode(value, “UTF-8”) 을 사용해서 한글을 저장합니다.
- 쿠키에서 정보를 읽어올 때는 URLDecoder.decoder(value, “UTF-8”) 를 사용하면 됩니다.
- 그리고 jsp 페이지 상단에는 꼭 <%@page import=”java.net.URLEncoder”%> 를 해주셔야 합니다.
1.쿠키 생성 - addCookie.jsp
<%@page import="java.net.URLEncoder"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>addCookie</title>
</head>
<body>
<h1>addCookie - 쿠키에 이름 저장하기</h1>
<%
//URLEncoder.encode(value, "UTF-8")
String name = URLEncoder.encode("홍길동", "UTF-8"); //한글입력 처리
Cookie c1 = new Cookie("name", name);
response.addCookie(c1);
%>
<%
Cookie c2 = new Cookie("address", "daejeon");
response.addCookie(c2);
%>
<a href="getCookie.jsp">getCookie 페이지로</a>
</body>
</html>
2.쿠키에 저장된 정보 읽어오기 - getCookie.jsp
<%@page import="java.net.URLDecoder"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>getCookie - Cookie 에서 데이터 가져오기</title>
</head>
<body>
<h1>Cookie 에서 데이터 가져오기</h1>
<%
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie c : cookies) {
out.print("cookie name : " + c.getName() + "<br>");
//URLDecoder.decoder(value, "UTF-8")
out.print("cookie value : " + URLDecoder.decode(c.getValue(), "UTF-8") + "<br>");
}
}
%>
<a href="index.jsp">이전 페이지 가기</a>
</body>
</html>