본문 바로가기

국비필기노트/jsp

Application, Cookie, Session 저장공간

우리가 이런 계산기를 만든다고 생각해보자.

 

 

 

 

그 계산기에는 값을 입력할 input창이 있을 것이고 +와 - 버튼이 있으르 것이다.

여기서 우리가 "1+2-3= "을 계산하고싶다면?  1을 누르고 +를 누르고 2를 누르고 -를 누르고 3을 누른 후 =를 누를것이다.

이 때 우리는 =을 누르면 0이 나올것을 생각하지만 사실 우리는 1과2를 담을 저장공간을 설정해주지않았기에 우리가 생각한 답과는 다른 결과가 나올 것이다.

 

컴퓨터에는 이러한 데이터를 담을 저장공간이 3가지가 있다. 

 

 

 

1. application

 

 

이클립스에서 하나의 project가 하나의 Application이라고 생각하면 되며, 하나의 Server에는 여러개의 Web Application이 존재할 수 있다. 

하나의 application이 생성되고 소멸될 때 까지 정보를 유지한다.

 

 

 

2. session

 

 

application은 서버 내부에 저장을 하지만 session은 하나의 웹 브라우저의 정보를 유지하기 위한 세션정보를 브라우저에 저장한다.

 

예를들어 브라우저를 열어서 로그인을 했다고해보자.우리가 따로  로그아웃을 하지않는다면 로그인상태로 계속 웹이 이어진다. 브라우저를 닫아야지만 로그아웃이 된다. 이는 로그인 정보를 세션이라고 하는 저장공간에 담았고 세션은 브라우저에 정보를 저장하기 때문이다.

 

세션은 브라우저마다 ID값이 다르다는 특징이 있다.

 

 

 

3. cookie

 

 

데이터를 사용자 로컬 PC에 저장을 한다. 그래서 우리가 인터넷을 하면서 쿠키저장에 질문이 나오는 이유도 사용자 PC에 데이터를 저장해야하기때문이다.

 

  • 생성: 웹 서버에서 쿠키를 생성하고 쿠키에 응답 데이터를 담아 웹 브라우저에 전송한다.
  • 저장: 웹 브라우저는 응답 데이터를 담고 있는 쿠키를 메모리나 파일로 저장한다.
  • 전송: 웹 브라우저는 쿠키 요청이 있을 때 마다 웹 서버에 전송한다. 웹 서버는 쿠키를 사용하여 필요한 작업을 수행 할 수 있다

쿠키의 동작방식은 생성, 저장, 전송 순으로 진행되는데 웹 서버로 사용자가 요청을 보낼 때 쿠키값을 요청헤더에 담아서 사용자가 전송하는 형태이다.

 

  • 클라이언트의 일정 폴더에 정보를 저장하기 때문에 서버의 부하를 줄일 수 있다.
  • 정보가 사용자 컴퓨터에 저장되기 때문에 보안에 위협을 받을 수 있다.
  • 데이터 저장 용량에 제한이 있다. 소용량(과자부스러기처럼 작은 값)
  • 일반 사용자가 브라우저 내의 기능인 "쿠키차단"을 사용하면 무용지물이다.

쿠키는 장단점이 명확한 데이터저장기능이다. 장단점을 잘 숙지하고 적합한 상황에 맞추어 사용한다.

 

 

정보를 담는 방법

 

 

*Html

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <form action="calc4" 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>
cs
 

*Application에 저장 코드 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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("/calc4")
public class CalcServlet extends HttpServlet{
 
    @Override
    protected void service(HttpServletRequest arg0, HttpServletResponse arg1) 
            throws ServletException, IOException {
        
        
        arg0.setCharacterEncoding("UTF-8"); //요청에 대한 한글처리
        
        arg1.setCharacterEncoding("UTF-8"); //응답에 대한 한글처리
        arg1.setContentType("text/html charset=UTF-8"); 
        
       //applicaiton에서 객체 받아오기
        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("=")) {
            //application에 저장된 값
            int x = (Integer)application.getAttribute("value");
            //2번째로 요청보낸값
            int y = value;
            String operator = (String)application.getAttribute("op");
            
            int result = 0;
            
            if(operator.equals("+")) {
                result = x + y;
            }else {
                result = x - y;
            }
            
            arg1.getWriter().println("결과값 : " + result);
            
        }else { //op값이 + , - 면
            application.setAttribute("value", value);
            application.setAttribute("op", op);
        }
        
        
        
        
 }
}
 
cs

 

 

*session 저장코드

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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("/calc2")
public class CalcServlet2 extends HttpServlet{
 
    @Override
    protected void service(HttpServletRequest arg0, HttpServletResponse arg1) 
            throws ServletException, IOException {
        
        
        arg0.setCharacterEncoding("UTF-8"); //요청에 대한 한글처리
        
        arg1.setCharacterEncoding("UTF-8"); //응답에 대한 한글처리
        arg1.setContentType("text/html charset=UTF-8"); 
        
        //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("=")) {
            //application에 저장된 값
            int x = (Integer)session.getAttribute("value");
            //2번째로 요청보낸값
            int y = value;
            String operator = (String)session.getAttribute("op");
            
            int result = 0;
            
            if(operator.equals("+")) {
                result = x + y;
            }else {
                result = x - y;
            }
            
            arg1.getWriter().println("결과값 : " + result);
            
        }else { //op값이 + , - 면
            session.setAttribute("value", value);
            session.setAttribute("op", op);
        }
        
        
        
        
 }
}
 
cs

 

 

Application과 Session의 코드 구조는 동일하다.

 

*값 설정하기

 

  • Application: Application.setAttribute("어플리케이션아이디", 어플리케이션에 넣을 값);
  • Session: session.setAttribute("세션아이디", 세션에 넣을 값);

 

 

*객체 받아오기

 

  • Application: ServletContext application = arg0.getServletContext( );
  • Session: HttpSession session = arg0.getSession( );

 

 

*저장된 값 꺼내오기

 

  • Application: application.getAttribute("user_id");
  • Session: session.getAttribute("user_id");

 

 

*유지시간 설정(초단위)

 

  • Session: session.setMaxInactiveInterval(60*60) //    (60*): 60초 / (60*60): 60분 / (-1): 무제한

 

 

*세션값 삭제

 

  • Session: session.removeAttribute("user_id");      //특정ID값 제거
  •             session.invalidate( );                       //세션 전체 제거

 

 

*Application과 Session의 차이 

 

Session에 저장한다는 것은 브라우저 영역 어딘가에 저장을 한다는 것이다.

만약 Chrom과 Edge에 계산기를 틀고 Chrom엔 5+ 를 넣고 Edge 브라우저에 2 = 를 넣었다면 Edge에는 500 서버 에러가 출력된다. Chrom과 Edge는 다른 브라우저이기때문에 서로가 저장되어있는 값을 꺼내올 수 없기 때문에 나타나는 에러다. 단, Application은 어플리케이션 저장소에 저장이 되기때문에 서로 다른 브라우저로 계산기를 실행해도 문제없이 결과값이 출력된다. 

 

 

 

 

*Cookie 저장코드

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
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("/calc3")
public class CalcServlet3 extends HttpServlet{
 
    @Override
    protected void service(HttpServletRequest arg0, HttpServletResponse arg1) 
            throws ServletException, IOException {
        
        
        arg0.setCharacterEncoding("UTF-8"); 
        
        arg1.setCharacterEncoding("UTF-8");
        arg1.setContentType("text/html charset=UTF-8"); 
        
 
        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("=")) {
            //Cookies 저장된 값
            int x = 0;
            int y = value;
            
            //Cookies 꺼내기
            for(Cookie c : cookies) {
            if(c.getName().equals("value")) {
                x = Integer.parseInt(c.getValue());
                break;
            }
            }
            
            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;
            }
            
            arg1.getWriter().println("결과값 : " + result);
            
        }else { //op값이 + , - 면
            Cookie valueCookie = new Cookie("value",String.valueOf(value)); //쿠키는 문자열만 저장가능 int->String
            Cookie opCookie = new Cookie("op",op); //op는 문자열이라 변경x
            
            //사용자에게 쿠키 전달
            arg1.addCookie(valueCookie);
            arg1.addCookie(opCookie);
        }
        
        
        
        
 }
}
 
cs

 

 

 

쿠키는 해당 사진과 같이 클라이언트와 서버가 계속해서 쿠키를 주고받는 형태로 데이터가 전송된다.

그래서 쿠키는 앞의 Application과 session 의 방법과는 조금 차이가 있다. 

 

먼저, 클라이언트가 5+2라는 수식을 계산하기 위해 5+라는 값을 쿠키로 넘어준다.

그럼 쿠키는 Cookie[] cookies = arg0.getCookies(); 로 해당 값을 받는다. 단, 문제는 해당 값을 다시 클라이언트로 넘겨줘야하는데 그 값이 없는 것이다! 그 때  

 

 

1
2
3
4
5
6
7
else { //op값이 + , - 면
            Cookie valueCookie = new Cookie("value",String.valueOf(value));
            Cookie opCookie = new Cookie("op",op);
            
            //사용자에게 쿠키 전달            arg1.addCookie(valueCookie);
            arg1.addCookie(opCookie);
        }
cs

 

해당 else문 로직을 타서 사용자에게 cookie를 보내준다.

그리고 사용자가 요청(2 = ) 이라는 요청을 보내면 기존의 5+까지 같이 넣어서 5+2라는 완성된 수식으로 결과값을 보내주는 것이다. 

 

 

 

페이지전환

 

1
2
3
4
5
6
7
8
9
10
else { //op값이 + , - 면
            Cookie valueCookie = new Cookie("value",String.valueOf(value));
            Cookie opCookie = new Cookie("op",op);
            
            //사용자에게 쿠키 전달
            arg1.addCookie(valueCookie);
            arg1.addCookie(opCookie);
            
            arg1.sendRedirect("calc3.html");
        }
cs

 

예를들어 Cookie예시의 else 를 가져왔다.

기존의 화면은 2 + 누르면 흰 배경이 나타나고 다시 뒤로가야하는 불편한 구조였지만

redirect를 사용함으로 = 을 눌러야지만 결과값 페이지로 넘어갈 수 있다.

'국비필기노트 > jsp' 카테고리의 다른 글

jsp_MVC패턴  (0) 2022.06.03
jsp_jsp태그  (0) 2022.06.01
jsp_attribute scope  (0) 2022.06.01
jsp_액션태그, 디렉티브태그,forward,redirect  (0) 2022.06.01
jsp_Servlet, Filter  (0) 2022.05.26