JSP로 쿠키를 설정하려면 세 단계를 거쳐야 합니다. -
1단계:쿠키 개체 만들기
쿠키 이름과 쿠키 값을 사용하여 쿠키 생성자를 호출합니다. 둘 다 문자열입니다.
Cookie cookie = new Cookie("key","value"); 이름이나 값에는 공백이나 다음 문자가 포함되어서는 안 됩니다. -
[ ] ( ) = , " / ? @ : ;
2단계:최대 연령 설정
setMaxAge를 사용합니다. 쿠키가 유효한 기간(초)을 지정합니다. 다음 코드는 24시간 동안 쿠키를 설정합니다.
cookie.setMaxAge(60*60*24);
3단계:HTTP 응답 헤더에 쿠키 보내기
response.addCookie를 사용합니다. 다음과 같이 HTTP 응답 헤더에 쿠키를 추가하려면
response.addCookie(cookie);
예시
<%
// Create cookies for first and last names.
Cookie firstName = new Cookie("first_name", request.getParameter("first_name"));
Cookie lastName = new Cookie("last_name", request.getParameter("last_name"));
// Set expiry date after 24 Hrs for both the cookies.
firstName.setMaxAge(60*60*24);
lastName.setMaxAge(60*60*24);
// Add both the cookies in the response header.
response.addCookie( firstName );
response.addCookie( lastName );
%>
<html>
<head>
<title>Setting Cookies</title>
</head>
<body>
<center>
<h1>Setting Cookies</h1>
</center>
<ul>
<li><p><b>First Name:</b>
<%= request.getParameter("first_name")%>
</p></li>
<li><p><b>Last Name:</b>
<%= request.getParameter("last_name")%>
</p></li>
</ul>
</body>
</html> 위의 코드를 main.jsp에 넣어봅시다. 파일을 만들고 다음 HTML 페이지에서 사용하십시오 -
<html> <body> <form action = "main.jsp" method = "GET"> First Name: <input type = "text" name = "first_name"> <br /> Last Name: <input type = "text" name = "last_name" /> <input type = "submit" value = "Submit" /> </form> </body> </html>
위의 HTML 콘텐츠를 hello.jsp 파일에 보관 hello.jsp를 입력합니다. 및 main.jsp
출력

이름과 성을 입력한 다음 제출 버튼을 클릭하십시오. 이렇게 하면 화면에 이름과 성이 표시되고 두 개의 쿠키 firstName도 설정됩니다. 및 성 . 이 쿠키는 다음에 제출 버튼을 클릭할 때 서버로 다시 전달됩니다.