<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Cookie Main</title> </head> <body> <h2>로그인</h2> <form method="post" action="CoockieBtn.jsp"> <table border="1"> <tr height="50"> <td height="80" align="center">아이디</td> <td><input type="text" name="id"/></td> </tr> <tr height="50"> <td height="80" align="center">비밀번호</td> <td><input type="password" name="pass"/></td> </tr> <tr> <td height="50" colspan="2" align="center">아이디 저장<input type="checkbox" name="checkbox"></td> </tr> <tr> <td height="50" colspan="2" align="center"> <input type="submit" value="로그인"></td> </tr> </table> </form> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <body> <% request.setCharacterEncoding("UTF-8"); String id = request.getParameter("id"); String checkbox = request.getParameter("checkbox"); if(checkbox!=null){ //체크박스가 클릭되어 있으면 Cookie cookie = new Cookie("id",id); //유효시간 설정 cookie.setMaxAge(60*10); //10분간 유효 //사용자에게 쿠키값을 넘겨줌. response.addCookie(cookie); response.sendRedirect("Main.jsp"); }else{ response.sendRedirect("Main.jsp"); } %> </body> </html>
<% request.setCharacterEncoding("UTF-8"); String id = ""; //쿠키 배열 생성 Cookie[] cookies = request.getCookies(); if(cookies !=null){ for(int i=0;i<cookies.length;i++){ if(cookies[i].getName().equals("id")){ //저장된 쿠키 이름이 "id" >인 경우 id = cookies[i].getValue(); //쿠키값을 가져옴 break; } } } %>
<table border="1"> <tr height="50"> <td height="80" align="center">아이디</td> <td><input type="text" name="id" value=<%=id %>></td> </tr>
//유효시간 설정 cookie.setMaxAge(0); //0으로 설정해 바로 만료