본문 바로가기

서버/Servlet-JSP
[Servlet-JSP] Cookie

// Cookie

- 서버와 웹브라우저의 연결이 끊겼을 때 어떤 정보를 지속적으로 유지하기 위한 수단으로 사용한다.

- 서버에서 생성하여 클라이언트 측에 특정 정보를 저장한다.

- 서버에 요청할 때마다 쿠키의 속성값을 참조 또는 변경할 수 있다.

- 용량이 4kb로 제한적이며, 300개까지 데이터 정보를 가질 수 있다.

- 서블릿마다 다른 Cookie를 사용하기 위해 url 설정(path 옵션)

valueCookie.setPath("/"); // 모든 url

opCookie.setPath("/calc2"); //특정 url


~ setMaxAge() : 쿠키의 유효기간을 설정한다.(초 단위)
~ setpath() : 쿠키 사용의 유효 디렉토리를 설정한다.
~ setValue() : 쿠키의 값을 설정한다.
~ setVersion() : 쿠키의 버전을 설정한다.
~ getMaxAge() : 쿠키의 유효기간 정보를 얻어온다.
~ getName() : 쿠키의 이름을 얻어 온다.
~ getPath() 쿠키 사용의 유효 디렉토리 정보를 얻어온다.
~ getValue() : 쿠키의 값을 얻어온다.
~ getVersion() :  쿠키의 버전을 얻어온다.


		} else { //operator가 + 또는 -			
			Cookie valueCookie = new Cookie("value", String.valueOf(v));
			Cookie opCookie = new Cookie("op", op);
			valueCookie.setPath("/");
			opCookie.setPath("/");
			response.addCookie(valueCookie); //클라이언트에 전달
			response.addCookie(opCookie);
			
		}		
	}
}

valueCookie.setMaxAge(60*60*24);

package com.sorrelcalc.web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/calcpage")
public class CalcPage extends HttpServlet{
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		Cookie[] cookies = request.getCookies();

		String exp = "0"; 		
		if(cookies != null) {
			for (Cookie c : cookies) {
				if (c.getName().equals("exp")) {
					exp = c.getValue();
					break;
				}
			}
		}

		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter out = response.getWriter();

		out.write("<!DOCTYPE html>");
		out.write("<html>");
		out.write("<head>");
		out.write("<meta charset=\"UTF-8\">");
		out.write("<title>Insert title here</title>");
		out.write("<style>");
		out.write("input {");
		out.write("width: 50px;");
		out.write("height: 50px;");
		out.write("}");
		out.write(".output{");
		out.write("height:50px;");
		out.write("background:#e9e9e9;");
		out.write("font-size:24px;");
		out.write("font-weight:bold;");
		out.write("text-align:right;");
		out.write("padding:0px 5px; ");
		out.write("}");
		out.write("</style>");
		out.write("</head>");
		out.write("<body>");
		out.write("<form action=\"calc3\" method=\"post\">");
		out.write("		<table>");
		out.write("			<tr>");
		out.printf("				<td class=\"output\" colspan = \"4\">%s</td>", exp); //동적
		out.write("			</tr>");
		out.write("			<tr>");
		out.write("				<td><input type=\"submit\" name=\"operator\" value=\"CE\" /></td>");
		out.write("				<td><input type=\"submit\" name=\"operator\" value=\"C\" /></td>");
		out.write("				<td><input type=\"submit\" name=\"operator\" value=\"←\" /></td>");
		out.write("				<td><input type=\"submit\" name=\"operator\" value=\"/\" /></td>");
		out.write(			"</tr>");
		out.write("			<tr>");
		out.write("				<td><input type=\"submit\" name=\"value\" value=\"7\" /></td>");
		out.write("				<td><input type=\"submit\" name=\"value\" value=\"8\" /></td>");
		out.write("				<td><input type=\"submit\" name=\"value\" value=\"9\" /></td>");
		out.write("				<td><input type=\"submit\" name=\"operator\" value=\"*\" /></td>");
		out.write("			</tr>");
		out.write("			<tr>");
		out.write("				<td><input type=\"submit\" name=\"value\" value=\"4\" /></td>");
		out.write("				<td><input type=\"submit\" name=\"value\" value=\"5\" /></td>");
		out.write("				<td><input type=\"submit\" name=\"value\" value=\"6\" /></td>");
		out.write("				<td><input type=\"submit\" name=\"operator\" value=\"-\" /></td>");
		out.write("			</tr>");
		out.write("			<tr>");
		out.write("				<td><input type=\"submit\" name=\"value\" value=\"1\" /></td>");
		out.write("				<td><input type=\"submit\" name=\"value\" value=\"2\" /></td>");
		out.write("				<td><input type=\"submit\" name=\"value\" value=\"3\" /></td>");
		out.write("				<td><input type=\"submit\" name=\"operator\" value=\"+\" /></td>");
		out.write("			</tr>");
		out.write("			<tr>");
		out.write("				<td></td>");
		out.write("				<td><input type=\"submit\" name=\"value\" value=\"0\" /></td>");
		out.write("				<td><input type=\"submit\" name=\"dot\" value=\".\" /></td>");
		out.write("				<td><input type=\"submit\" name=\"operator\" value=\"=\" /></td>");
		out.write("			</tr>");
		out.write("		</table>");
		out.write("</form>"); 	
		out.write("</body>");
		out.write("</html>");

	}
}

 

package com.sorrelcalc.web;
	
import java.io.IOException;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
	
@WebServlet("/calc3")
public class Calc3 extends HttpServlet{
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Cookie[] cookies = request.getCookies(); 		

		String value = request.getParameter("value");
		String operator = request.getParameter("operator");		
		String dot = request.getParameter("dot");		

		String exp = "";	
		if(cookies != null) 
			for (Cookie c : cookies) 
				if (c.getName().equals("exp")) {
					exp = c.getValue();
					break;
				}

		if(operator != null && operator.equals("=" )) {
			ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
			try {
				exp = String.valueOf(engine.eval(exp));
			} catch (ScriptException e) {
				e.printStackTrace();
			}
		} else if (operator != null && operator.equals("C" )) {
			exp = ""; //쿠키 삭제
		} else {
			exp += (value == null)? "" : value;
			exp += (operator == null)? "" : operator;
			exp += (dot == null)? "" : dot;
		}
		Cookie expCookie = new Cookie("exp", exp);
		if (operator != null && operator.equals("C" )) 
			expCookie.setMaxAge(0); //쿠키 삭제
		response.addCookie(expCookie);
		response.sendRedirect("calcpage");
	}
}

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

	<%
		Cookie cookie = new Cookie("cookieN", "cookieV");
		cookie.setMaxAge(60*60); //한 시간
		response.addCookie(cookie);
	%>
	
	<a href="cookieget.jsp">get cookie</a>

</body>
</html>

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<%
	Cookie[] cookies = request.getCookies();

	for(Cookie c : cookies) {
	    out.println("cookie name = " + c.getName()+"<br>");
	    out.println("cookie value = " + c.getValue()+"<br>");
	    out.println("cookie inter = " + c.getMaxAge()+"<br>");
	}
%>

<a href="cookiedel.jsp">delete cookie</a>

</body>
</html>

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<%
	Cookie[] cookies = request.getCookies();
	for(Cookie c : cookies) {
	    c.setMaxAge(0);
	    response.addCookie(c);
	}
	
%>

	<a href="cookiecheck.jsp">check cookie</a>

</body>
</html>

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<%
	Cookie[] cookies = request.getCookies();

	if(cookies != null) {
	    for(Cookie c : cookies) {
	  	    out.println("cookie name = " + c.getName()+"<br>");
	  	    out.println("cookie value = " + c.getValue()+"<br>");
	  	    out.println("cookie inter = " + c.getMaxAge()+"<br>");
	  	}
	} else {
	    out.println("쿠키가 없습니다.");
	}
%>

</body>
</html>

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

	<form action="loginok.jsp" method="post">
		<div>아이디: <input type="text" name="id"></div>
		<div>비밀번호: <input type="password" name="pw"></div>	
		<input type="submit" value="로그인">
	</form>

</body>
</html>

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

	<%
		String id = request.getParameter("id");
		String pw = request.getParameter("pw");	
		
		if(id.equals("sorrel012") && pw.equals("1234")){
		    Cookie cookie = new Cookie("id", id);
		    cookie.setMaxAge(60*10);
		    response.addCookie(cookie);
		    response.sendRedirect("loginsuccess.jsp");
		} else {
		    response.sendRedirect("login.jsp");
		}
	%>

</body>
</html>

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

	<%
		Cookie[] cookies = request.getCookies();
		
		for(Cookie c : cookies) {
		    String id = c.getValue();
		    if(id.equals("sorrel012")) {
		        out.println(id + "님 안녕하세요.<br>");
		    }
		}
		
	%>
	
	<a href="logout.jsp">로그아웃</a>

</body>
</html>

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

	<%
	
		Cookie[] cookies = request.getCookies();
		
		if(cookies != null) {
		    for(Cookie c : cookies) {
		        String id = c.getValue();
		        if(id.equals("sorrel012")) {
		            c.setMaxAge(0);
		            response.addCookie(c);
		        }
		    }
		}
		
		response.sendRedirect("logoutsuccess.jsp");
	%>

</body>
</html>

 

<%@page import="java.util.Enumeration"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

	<%
		Cookie[] cookies = request.getCookies();
		
		int i = 0;
		if(cookies != null) {
		    for(Cookie c : cookies) {
		        String id = c.getValue();
		        if(id.equals("sorrel012")) {
		            i++;
		            break;
		        }
		    }
		}	
		
		if(i == 0) {		  	
	%> 
		<h2>로그아웃이 완료되었습니다.</h2>
		
		<%} %>

</body>
</html>