정보저장하기

전영덕·2023년 3월 26일
0

JSP

목록 보기
3/16
post-thumbnail

상태유지의 필요성

  • application, session, cookie

1. application

  • 하나의 프로젝트가 생성이 되고, 소멸될 때까지 계속 유지된다.
  • calc3이라는 계산기 프로그램만들기. application에 저장한다.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="calc3" 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>
package com.codingbox.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("/calc3")
public class MyServlet7 extends HttpServlet {

	@Override
	protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {

		// application 저장소 선언
		ServletContext application = arg0.getServletContext();
		
		String value_ = arg0.getParameter("value");
		String op = arg0.getParameter("operator");
		
		PrintWriter out = arg1.getWriter();
		int value = 0;
		if(!value_.equals("")) {	//빈값이 아닐 경우에 연산하기
			value = Integer.parseInt(value_);
		}
		
		if(op.equals("=")) {
			//계산
			int x = (Integer)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.printf("결과 값 : %d", result);
		} else {
		//application에다가 값을 저장하기
		application.setAttribute("value", value);
		application.setAttribute("op", op);
		}
	}
}
  1. session
    2-1. session이란
  • 하나의 웹 브라우저의 정보를 유지하기 위한 세션 정보를 저장
    (브라우저 종료 시 종료, 클라이언트 로그인 정보)
  • 내장객체로서 브라우저마다 한 개씩 존재하고, 고유한 sessionID 생성 후 정보를 추출한다.
    2-2. 장점 : 서버에서 접근할 수 있기 때문에 보안성이 좋고, 저장 용량의 한계가 거의 없다.
    2-3. 단점 : 서버에 데이터를 저장하므로 부하가 걸릴 수 있다.

2-4. session 사용하기

  • 세션값 설정
    session.setAttribute("설정이름", 값);

  • 세션 유지시간 설정하기(초 단위)
    1) 60분동안 저장
    session.setMaxInactiveInterval(60*60);
    2) 무한대로 설정
    session.setMaxInactiveInterval(-1);

  • 세션에 저장된 값 가져오기
    session.getAttribute("설정이름")

  • 세션삭제
    session.removeAttribute("설정이름")
    //세션 전체 제거
    session.invalidate();

2-5. application과 비교하여 session에 값저장하는 것 예제

  • 일단 html파일
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="calc" 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>
  • 웹서블릿 자바파일
package com.codingbox.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("/calc")
public class MyServlet extends HttpServlet{

	@Override
	protected void service(HttpServletRequest arg0, 
			HttpServletResponse arg1) throws ServletException, IOException {

		//application 저장소 선언
		//ServletContext application = arg0.getServletContext();
		
		//session
		HttpSession session = arg0.getSession();
		
		String value_ = arg0.getParameter("value");
		String op = arg0.getParameter("operator");
		
		PrintWriter out = arg1.getWriter();
		int value = 0;
		
		if(!value_.equals("")) {
			 value = Integer.parseInt(value_);
		}
		
		if( op.equals("=") ) {
			// 계산
//			int x = (Integer)application.getAttribute("value");
			int x = (Integer)session.getAttribute("value");
			int y = value;
//			String operator = (String)application.getAttribute("op");
			String operator = (String)session.getAttribute("op");
			
			int result = 0;
			
			if(operator.equals("+")) {
				result = x + y;
			} else {
				result = x - y;
			}
			
			out.printf("결과값 : %d", result);
		} else {
			//application 값 저장
//			application.setAttribute("value", value);
//			application.setAttribute("op", op);
			session.setAttribute("value", value);
			session.setAttribute("op", op);
		}
	}
}

3. 쿠키(Cookie)

3-1. 쿠키란

  • 웹브라우저가 보관하고 있는 데이터로 웹 서버에 요청을 보낼 때 쿠키를 헤더에 담아서 전송한다.
    3-2. 장점
  • 클라이언트의 일정 폴더에 정보를 저장하기 때문에 서버의 부하를 줄일 수 있다.
    3-3. 단점
  • 정보가 사용자 컴퓨터에 저장되기 때문에 보안에 위협을 받을 수 있다.
  • 데이터 저장 용량에 제한이 있다.
  • 과자 부스러기처럼 작은 값을 저장할 수 있다.
  • 일반 사용자가 브라우저 내의 기능인 "쿠키차단"을 사용하면 무용지물이다.

3-4. application, session과 비교한 cookie예시

  • html파일 앞에와 같다.action만 calc2로 다름
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="calc2" 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>
  • 웹서블릿 자바파일
package com.codingbox.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("/calc2")
public class MyServlet2 extends HttpServlet {

	@Override
	protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {

//		application 저장소 선언
//		ServletContext application = arg0.getServletContext();

//		session에 저장해보자, 이것도 request에서 꺼내오자
//		HttpSession session = arg0.getSession();

//		Cookie 선언
		Cookie[] cookies = arg0.getCookies();

		String value_ = arg0.getParameter("value");
		String op = arg0.getParameter("operator");

		PrintWriter out = arg1.getWriter();
		int value = 0;
		
		if (!value_.equals("")) { // 빈값이 아닐 경우에 연산하기
			value = Integer.parseInt(value_);
		}

		if (op.equals("=")) {
			//계산 하는 부분
//			int x = (Integer)application.getAttribute("value");
//			int y = value;
//			String operator = (String)application.getAttribute("op");

//			int x = (Integer)session.getAttribute("value");
//			int y = value;
//			String operator = (String)session.getAttribute("op");

//0번째가 이거맞다면 이렇게 해도된다. 근데 아닐 수도 있자나? 여기저기 막 돌아다닌다거나한다면말이야
//			Cookie c = cookies[0];
//			if(c.getName().equals("value")) {
//				x = Integer.parseInt(c.getValue());
//			}

			int x = 0;

//			for문의 i번째 까지 써서 해도되지만 아래 방법이 훨씬 간단해서 많이쓴다.
			for (Cookie c : cookies) {
				if (c.getName().equals("value")) {
					x = Integer.parseInt(c.getValue());
					break;
				}
			}

			int y = value;
			
			String operator = "";
			for (Cookie c : cookies) {
				if (c.getName().equals("op")) {
					operator = c.getValue();
					break;
				}
			}

			int result = 0;

			if (operator.equals("+")) {
				result = x + y;
			} else {
				result = x - y;
			}

			out.printf("결과 값 : %d", result);
		} else {
//		application에다가 값을 저장하기	
//		application.setAttribute("value", value);
//		application.setAttribute("op", op);

//		session.setAttribute("value", value);
//		session.setAttribute("op", op);

			// cookie로 저장, 저장시 문자열 형태만 사용
			Cookie valueCookie = new Cookie("value", String.valueOf(value));
			Cookie opCookie = new Cookie("op", op);
			// 사용자에게 cookie전달
			arg1.addCookie(valueCookie);
			arg1.addCookie(opCookie);
		}
	}
}

4. 쿠키vs 세션

  • 쿠키
    클라이언트(=접속자PC)에 저장
    저장형식 : text
    만료시점 : 쿠키 저장시 설정
    사용자원 : 클라이언트 리소스
    용량제한 : 총 300개 (제한적이라 큰것을 저장할 수는 없다.)
    속도 : 세션보다는 빠르다.
    보안 : 세션보다는 안 좋다.

  • 세션
    웹서버에 저장
    저장형식 : Object
    만료시점 : 브라우저 종료시 설정
    사용자원 : 웹 서버 리소스
    용량 제한 : 서버가 허용하는 용량제한(무제한에 가깝다)
    속도 : 쿠키보다는 느리다.
    보안 : 쿠키보다는 좋다.

0개의 댓글