너와 나의 연결고리, JSP 🔗(4) - 어플리케이션, 세션, 쿠키

joyfulwave·2022년 10월 12일
0

이제 진짜 웹 서버와 연결해 볼 차례




📚 상태유지의 필요성

HTTP 통신은 2가지의 특징이 있어요.

⚫ 비연결지향

클라이언트의 요청에 대한 서버의 응답이 처리되면 둘의 연결은 끊어지게 되는데요. 불필요한 커네션으로 인한 리소스의 낭비가 생기지 않도록 비연결을 지향해요.

⚫ 상태없음

클라이언트와 서버의 커넥션이 끊어지면 클라이언트의 상태, 정보 등을 유지하지 않아요.

하지만, 클라이언트의 상태를 알아야 할 경우(예: 인증, 로그인 유지 등)가 생기기 때문에 상태를 유지할 필요가 생겼어요.

그때 application, session, cookie를 사용해요.




📚 application

📌 application(어플리케이션)

  • tomcat(server, 서버)에 저장
  • 하나의 application이 생성되고 소멸될 때까지 계속 유지해요.
  • eclipse에서 하나의 project가 하나의 application이라고 생각하면 되고, 하나의 server에는 여러개의 web application이 존재할 수 있어요.



📚 session

📌 session(세션)

  • 브라우저에 저장
  • 하나의 웹 브라우저의 정보를 유지하기 위한 세션 정보를 저장
  • 브라우저 종료 시 종료
  • 클라이언트 로그인 정보를 저장하는데 사용해요.
  • 내장객체로서 브라우저마다 한개씩 존재하고, 고유한 sessionID 생성 후 정보를 추출해요.

📌 session의 사용

⚫ 값 설정

session.setAttribute("설정한 세션아이디", 세션에 넣을 값);

⚫ 시간 설정

  session.setMaxInactiveInterval(60*60); 	// 60분동안 세션 유지
  session.setMaxInactiveInterval(-1); 	// 세션의 시간을 무한대로 설정

⚫ 값 가져오기

session.getAttribute("설정한 세션아이디");

⚫ 값 삭제

session.removeAttribute("설정한 세션아이디");
session.invalidate(); 	// 세션 전체 제거, 무효화



📚 cookie

⚫ cookie(쿠키)

-> 저장위치 : 클라이언트(=접속자 pc)
-> 저장형식 : text
-> 만료시점 : 쿠키 저장시 설정(브라우저가 종료되도, 만료시점이 지나지 않으면 자동 삭제가 안됌)
-> 용량제한 : 하나의 도메인당 20개
-> 속도    : 세션보다는 빠름
-> 보안    : 세션보다는 안좋다

⚫ session

-> 저장위치 : 해당 브라우저
-> 저장형식 : Object
-> 만료시점 : 브라우저 종료시 삭제(기간 지정은 가능)
-> 용량제한 : 서버가 허용하는 한 용량제한 없음
-> 속도    : 쿠키보다는 느림
-> 보안    : 쿠키보다 좋다



📚 활용 예제

⚫ 기본 예제 html

아래 파일의 결과를 각각 application, session, cookie로 구현해보자.
(application의 액션은 calc2 / session의 액션은 calc3 / cookie의 액션은 calc4)

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="calc2~4" method="post">
		<div>
			<label>입력 : </label>
			<input type="text" name="value">
		</div> 
		<div>
			<input type="submit" name="operator" value="+">
			<input type="submit" name="operator" value="-">
			<input type="submit" name="operator" value="=">
		</div>
	</form>
</body>
</html>

⚫ 출력방식

  1. 5 입력
  2. + 버튼 클릭 (application or session or cookie에 값 저장)
  3. 5 입력
  4. = 버튼 클릭 (application or session or cookie에 저장된 값과 연산하여 결과 출력)

⚫ 출력결과

10

📌 application

package com.koreait.web.servlet;

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

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

@WebServlet("/calc2")
public class MyServlet2 extends HttpServlet{
	@Override
	protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
		
//		application 저장소 선언
		ServletContext application = arg0.getServletContext();
		
		PrintWriter out = arg1.getWriter();
		
		String value_ = arg0.getParameter("value");
		String op = arg0.getParameter("operator");
		
		int value = 0;
		
		if(!value_.equals("")) {
			value = Integer.parseInt(value_);
		}
		
		// 계산
		if(op.equals("=")) {
			int x = (int) application.getAttribute("value");
			int y = value;
			
			String operator = (String) application.getAttribute("op");
			
			int result = 0;
			
			if(operator.equals("+")) { // 더하기 결과
				result = x + y;
			}else { // 빼기 결과
				result = x - y;
			}
			out.println("결과 값 : " + result);
		}else{ // + or - => application 영역에 값을 저장
			application.setAttribute("value", value);
			application.setAttribute("op", op);
		}
		
	}
}

📌 session

package com.koreait.web.servlet;

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

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

@WebServlet("/calc3")
public class MyServlet3 extends HttpServlet{
	@Override
	protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {

//		session 객체
		HttpSession session = arg0.getSession();
		
		PrintWriter out = arg1.getWriter();
		
		String value_ = arg0.getParameter("value");
		String op = arg0.getParameter("operator");
		
		int value = 0;
		
		if(!value_.equals("")) {
			value = Integer.parseInt(value_);
		}
		
		// 계산
		if(op.equals("=")) {
			int x = (int) session.getAttribute("value");
			int y = value;
			
			String operator = (String) session.getAttribute("op");
			
			int result = 0;
			
			if(operator.equals("+")) { // 더하기 결과
				result = x + y;
			}else { // 빼기 결과
				result = x - y;
			}
			out.println("결과 값 : " + result);
		}else{ // + or - => application 영역에 값을 저장
			session.setAttribute("value", value);
			session.setAttribute("op", op);
		}
		
	}
}
package com.koreait.web.servlet;

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

import javax.servlet.ServletContext;
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;
import javax.servlet.http.HttpSession;

@WebServlet("/calc4")
public class MyServlet4 extends HttpServlet{
	@Override
	protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {

//		session 객체
//		HttpSession session = arg0.getSession();
		
//		cookie
		Cookie[] cookies = arg0.getCookies();
		
		PrintWriter out = arg1.getWriter();
		
		String value_ = arg0.getParameter("value");
		String op = arg0.getParameter("operator");
		
		int value = 0;
		
		if(!value_.equals("")) {
			value = Integer.parseInt(value_);
		}
		
		// 계산
		if(op.equals("=")) {
			System.out.println(" = 조건 도착 ");
			int y = value;
			
			int x = 0;
			// cookies 꺼내기
            // for문 방식
			// cookie는 배열로 값이 담겨있기 때문에 배열로 꺼내온다.
//			Cookie c = cookies[0];
//			if( c.getName().equals("value")) {
//				x = Integer.parseInt(c.getValue());
//			}

			// forEach 방식			
			for(Cookie c : cookies) {
				if(c.getName().equals("value")) {
					x = Integer.parseInt(c.getValue());
					break; // 조건에 맞으면 for문을 끝냄
				}
			}
			
			String operator = "";
			
			for(Cookie c : cookies) {
				if(c.getName().equals("op")) {
					operator = c.getValue();
					break; // 조건에 맞으면 for문을 끝냄
				}
			}
			
			int result = 0;
			
			if(operator.equals("+")) { // 더하기 결과
				result = x + y;
			}else { // 빼기 결과
				result = x - y;
			}
			out.println("결과 값 : " + result);
		}else{ 
			System.out.println(" else 조건 도착 ");
			
			// cookie로 저장
			Cookie valueCookie = new Cookie("value", String.valueOf(value));
			Cookie opCookie = new Cookie("op", op);
			
//			사용자에게 cookie가 전달된다.
			arg1.addCookie(valueCookie);
			arg1.addCookie(opCookie);
			
			arg1.sendRedirect("calc4.html");
		}
		
	}
}



📚 정리

📌 application

  • 사용범위 : 전역 범위에서 사용하는 저장공간 (서버가 꺼지지만 않으면)
  • 생명주기 : WAS가 시작해서 종료할 때 까지

📌 session

  • 사용범위 : 세션 범위에서 사용하는 저장공간
  • 생명주기 : 세션이 시작해서 종료할 때 까지
  • 사용범위 : web 브라우저 별 지정한 path 범주 공간
  • 생명주기 : 브라우저에서 전달한 시간부터 만료 시간까지



포기하지 말고 JUST DO! ✔️




출처
https://media.giphy.com/media/dwmNhd5H7YAz6/giphy.gif
https://media.giphy.com/media/3o6Mb9EC7mNqXl9x7y/giphy.gif

0개의 댓글