본문 바로가기

서버/Servlet-JSP
[Servlet-JSP] 입력 데이터 - 상태 유지

- 서버 저장소
1. application  
2. session

- 클라이언트 저장소 
3. cookie

  Application Session Cookie
사용 범위 전역 범위 세션 범위에서 사용하는 저장 공간 웹 브라우저별 지정한 path 범주 공간
생명 주기 WAS가 시작해서 종료될 때까지 세션이 시작해서 종료될 때까지 브라우저에 전달한 시간부터 만료 시간까지
저장 위치 WAS 서버의 메모리 WAS 서버의 메모리 웹 브라우저의 메모리 또는 파일

1. application

- application 저장소 : 서블릿 컨텍스트

- 객체 사용 시 application 전역에서 사용 가능

- import javax.servlet.ServletContext;

ServletContext application =  request.getServletContext();

application.setAttribute("name1", 저장할 값);
int x = (Integer)application.getAttribute("name1");

 

 

//calc2.thml

<!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="v" />
		</div>
		<div>
			<input type="submit" name="operator" value="+" />
			<input type="submit" name="operator" value="-" />
			<input type="submit" name="operator" value="=" />
		</div>
	</form> 	
</body>
</html>

 

//Calc2.java

package com.sorrelcalc.web;

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 Calc2 extends HttpServlet{
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ServletContext application =  request.getServletContext();
		
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		
		PrintWriter out = response.getWriter();
		
		String v_ = request.getParameter("v");
		String op = request.getParameter("operator");		
		
		int v = 0;
		if(!v_.equals("")) v = Integer.valueOf(v_);
		
		if(op.equals("=")) {
			
			int x = (Integer)application.getAttribute("value");
			int y = v;
			String operator = (String)application.getAttribute("op");				
			
			int result = 0;
			
			if(operator.equals("+")) 
				result = x+y;
			else 
				result = x-y;
			out.println("계산 결과는 = " + result);
		} else { //operator가 + 또는 -
			application.setAttribute("value", v);
			application.setAttribute("op", op);
		}		
	}
}

2. session

- 세션에 저장한 변수
        > 전역 변수(페이지 간에 별도의 전달 과정 없이 언제든 입출력 가능)
        > 접속 종료 전까지 계속 유지가 된다.(상태 유지 도구 역할)
        
- 같은 프로그램이면 같은 사용자, 다른 프로그램이면 다른 사용자로 인식한다.

- 객체 사용 시 session 범주 내에서 사용 가능

- chrome 창 여러 개에서 실행하면 -> 같은 값 저장
    ~ chrome 창에서 저장한 값은 firefox에서 저장하지 않음(NullPointerException)

- import javax.servlet.http.HttpSession;

ServletContext application =  request.getServletContext();

application.setAttribute("name1", 저장할 값);
int x = (Integer)application.getAttribute("name1");

//calc2.thml

<!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="v" />
		</div>
		<div>
			<input type="submit" name="operator" value="+" />
			<input type="submit" name="operator" value="-" />
			<input type="submit" name="operator" value="=" />
		</div>
	</form> 	
</body>
</html>

 

//Calc2.java

package com.sorrelcalc.web;

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

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 Calc2 extends HttpServlet{
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		
		PrintWriter out = response.getWriter();
		
		String v_ = request.getParameter("v");
		String op = request.getParameter("operator");		
		
		int v = 0;
		if(!v_.equals("")) v = Integer.valueOf(v_);
		
		if(op.equals("=")) {
			
			int x = (Integer)session.getAttribute("value");
			int y = v;				
			String operator = (String)session.getAttribute("op");				
			
			int result = 0;
			
			if(operator.equals("+")) 
				result = x+y;
			else 
				result = x-y;
			out.println("계산 결과는 = " + result);
		} else { //operator가 + 또는 -
			session.setAttribute("value", v);
			session.setAttribute("op", op);
		}		
	}
}

3. cookie

a. 자바

- 쿠키 저장하기

Cookie cookie = new Cookie("c", String,valueOf(result));
reponse.addCookie(cookie); //브라우저에 전달


- 쿠키 읽기

Cookie[] cookies = request.getCookies();
String _c = "";

if (cookies != null) {
	for (Cookie cookie : cookies) {
	    if("c".equals(cookie.getName()))
        	_c = cookie.getValue();
	}
}

 

//calc2.thml

<!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="v" />
		</div>
		<div>
			<input type="submit" name="operator" value="+" />
			<input type="submit" name="operator" value="-" />
			<input type="submit" name="operator" value="=" />
		</div>
	</form> 	
</body>
</html>

 

//Calc2.java

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("/calc2")
public class Calc2 extends HttpServlet{
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Cookie[] cookies = request.getCookies(); 		
		
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		
		PrintWriter out = response.getWriter();
		
		String v_ = request.getParameter("v");
		String op = request.getParameter("operator");		
		
		int v = 0;
		if(!v_.equals("")) v = Integer.valueOf(v_);
		
		if(op.equals("=")) {
			
			int x = 0;
			int y = v;						
			
			for (Cookie c : cookies) { //쿠키 읽기
				if (c.getName().equals("value")) {
					x = Integer.valueOf(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;
			out.println("계산 결과는 = " + result);
			
		} else { //operator가 + 또는 -			
			Cookie valuecookie = new Cookie("value", String.valueOf(v));
			Cookie opcookie = new Cookie("op", op);
			response.addCookie(valuecookie); //클라이언트에 전달
			response.addCookie(opcookie);
			
		}		
	}
}

b. 자바 스크립트

<script src="js/cookie.js"></script>


※  위 코드를 추가한 후 작업한다.

- 쿠키 저장하기

setCookie(쿠키명, 값, 만료기간(날짜));



- 쿠키 읽기

 getCookie(쿠키명)

<%@ 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>
<link rel="stylesheet" href="https://me2.do/5BvBFJ57">
<style>
    /* 
    body {
        background-image: url(images/rect_icon01.png);
    }
     */
    table {
        background-color: white;
    }

</style>
</head>
<body>

    <h1>쿠키, Cookie</h1>
    
    <h2>배경화면 선택(테마)</h2>
    
    <table>
        <tr>
            <td><img src="images/rect_icon01.png"></td>
            <td><input type="radio" name="background" value="rect_icon01.png" checked></td>
        </tr>
        <tr>
            <td><img src="images/rect_icon02.png"></td>
            <td><input type="radio" name="background" value="rect_icon02.png"></td>
        </tr>
        <tr>
            <td><img src="images/rect_icon03.png"></td>
            <td><input type="radio" name="background" value="rect_icon03.png"></td>
        </tr>
    </table>    
    
    <hr>
    
    <div style="background-color: white;">
        <a href="ex20_cookie_one.jsp">첫 번째 페이지></a>
        <a href="ex20_cookie_two.jsp">두 번째 페이지></a>
        <a href="ex20_cookie_three.jsp">세 번째 페이지></a>
    </div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script src="js/cookie.js"></script>
<script>
    
    //key = value
    
    if(getCookie('background') == '') {
        //첫 방문
        setCookie('background', 'rect_icon01.png', 365);
    
    } else {
        //재방문
        $('body').css('background-image', `url(images/\${getCookie('background')})`);
        
        $('input[name=background]').each((index, item) => {
            if ($(item).val() == getCookie('background')) {
                $(item).prop('checked', true);
            } else {
                $(item).prop('checked', false);
            }
        });
        
    }
    
    $('input[name=background]').change(function() {
        
        //alert($(this).val());
        $('body').css('background-image', `url(images/\${$(this).val()})`);
        
        //선택한 테마 > 쿠키 지정        
        setCookie('background', $(this).val(), 365);
        
    });
    
</script>
</body>
</html>

// 서버 저장소

1. request : forward 관계에 있는 둘 사이에서 공유할 수 있는 저장소

2. page context : 해당 페이지 내에서 혼자 사용하는 저장소

3. session: 현재 세션에서 공유할 수 있는 저장소

4. application: 모든 세션, 모든 페이지에서 공유할 수 있는 저장소

+ 클라이언트 저장소 - cookie

우선순위: pageContext > request > session > application

'서버 > Servlet-JSP' 카테고리의 다른 글

[Servlet-JSP] 파일 업로드, 다운로드  (0) 2023.01.20
[Servlet-JSP] DAO, DTO, lombok  (0) 2023.01.20
[Servlet-JSP] Cookie  (0) 2023.01.15
[Servlet-JSP] Redirection  (0) 2023.01.13
JSP 내장 객체 - Session, Application  (0) 2023.01.13