반응형
Notice
Recent Posts
Recent Comments
Link
관리 메뉴

bro's coding

Servlet.Cookie/Session 본문

[IT]/Servlet

Servlet.Cookie/Session

givemebro 2021. 4. 8. 09:35
반응형

**Session 과 Cookie**
Http 특성 : Stateless ( 사용자 상태 정보를 유지하지 않는다 ) 

세션 관리 : 사용자 정보를 일정 조건동안 유지 

Cookie : 사용자 상태 정보를 클라이언트 측에 저장 
  저장 용량의 제한 ( 4KB ) ,  데이터타입은 문자열로 한정 
  Cookie 유효시간을 별도로 설정하지 않으면 
  브라우저 실행시에만 유효하다 
  Cookie 유효시간을 설정하면 
  그 유효시간 내에서만 쿠키를 사용할 수 있다 
  유효시간이 지나면 브라우저에서 삭제된다 ( 즉 사용 불가 ) 
  
  HttpSession 을 이용한 로그인 로그아웃 처리시에 
  내부적으로 Cookie가 이용된다 
  다시 말하면 HttpSession 은 내부적으로 Cookie를 이용한다는 의미임 

 

 

HttpSession : 사용자 상태 정보를 서버 측에 저장
저장 용량 및 데이터 타입의 제한이 없다
로그인 , 로그아웃시 세션이 이용된다 
WAS에 세션 유지 기간이 별도로 설정되어 있다 
(참고- apache tomcat 은 30분으로 설정 
tomcat/conf/web.xml 에 설정 
)
웹어플리케이션 별로 세션 유효시간을 설정할 수도 있다 
( WEB-INF/web.xml 에서 session-timeout 옵션으로 설정 ) 

세션유지기간(세션 생성 ~ 만료)
1) 지정한 유효시간(tomcat : 30분) 내에 새로운 요청이 없을 때 세션이 만료된다 
2) 브라우저를 종료 
3) 로그아웃을 실행할 때 ( session.invalidate() 를 통한 세션 무효화 )  

HttpSession 관련 주요 메서드 
request.getSession() : HttpSession 
-> 기존 세션이 있으면 기존 세션을 리턴 , 기존 세션이 없으면 새로 생성해서 리턴 

request.getSession(false) : HttpSession 
-> 기존 세션이 있으면 기존 세션을 리턴 , 기존 세션이 없으면 null 리턴 

session.setAttribute(name,value) 
-> 세션에 String 타입의 name과 Object 타입의 value를 할당 ( ex- 로그인 인증 후 인증정보(회원정보)를 저장 )

session.getAttribute(name) : Object 
-> 세션에 저장된 attribute 정보를 attribute name으로 attribute value를 반환

session.invalidate() 
-> 세션을 무효화(세션에 저장된 attribute를 사용할 수 없게 만든다) , 로그아웃시 사용 

 

 

 

 

package step1;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

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;

/**
 * Servlet implementation class SetCookieServlet
 */
@WebServlet("/SetCookieServlet")
public class SetCookieServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SetCookieServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		// 쿠키 생성
		// 현재 시간 정보를 value로 할당한다
		Date date = new Date();
		String time = date.toString().replace(" ", "-");
		Cookie cookie = new Cookie("time", time);
		// 쿠키 유효시간설정
		cookie.setMaxAge(60);
		// 생성한 쿠키를 클라이언트에 보내기 위해 아래 코드를 작성한다
		response.addCookie(cookie);
		out.println("<h3>");
		out.println(getServletName() + "이 쿠키를 클라이언트에게 전달<br><br>");
		out.println("저장한 시간정보:" + time + "<br><br>");
		out.println("<a href=GetCookieServlet>step2.GetCookieServlet에서 쿠키 정보 확인</a>");
		out.println("</h3>");
		out.close();
	}
}
package step2;

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;

/**
 * Servlet implementation class GetCookieServlet
 */
@WebServlet("/GetCookieServlet")
public class GetCookieServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public GetCookieServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.println("<h3>");
		out.println(getServletName() + "에서 클라이언트로부터  쿠키 정보확인<br><br>");
		// 클라이언트에 저장된 쿠키 정보를 가져온다
		Cookie[] cookie = request.getCookies();
		if (cookie != null) {
			boolean flag = false;
			for (int i = 0; i < cookie.length; i++) {
				if (cookie[i].getName().equals("time")) {
					flag = true;
					out.println(cookie[i].getValue() + "<br><br>");
					break;
				} // if
			} // for
			if (flag == false) {
				out.println("time 쿠키가 존재하지 않습니다<br><br>");
			}
		} else {
			out.println("쿠키가 존재하지 않습니다<br><br>");
		}
		out.println("<a href=SetCookieServlet>step1.SetCookieServlet에서 쿠키 정보 확인</a>");
		out.println("</h3>");
		out.close();
	}

}
package step3;

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

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;

/**
 * Servlet implementation class SessionOne
 */
@WebServlet("/SessionOne")
public class SessionOne extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SessionOne() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		// 세션을 생성한다 ( 기존 세션이 있으면 기존 세션을 반환 , 없으면 새로 생성 )
		HttpSession session = request.getSession();
		session.setAttribute("nick", "아이유");// 세션에 attribute 정보를 name, value로 할당
		out.println("SessionId:" + session.getId() + "<br><br>");
		out.println(getServletName() + "이 세션에 nick 정보 할당<br><br>");
		out.println("<a href=SessionTwo>SessionTwo에서 확인</a>");
		out.println("<a href=SessionThree>SessionThree에서 확인</a>");
		out.close();
	}

}
package step4;

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

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;

/**
 * Servlet implementation class SessionTwo
 */
@WebServlet("/SessionTwo")
public class SessionTwo extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SessionTwo() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		// 세션을 반환받는다 ( 기존 세션이 있으면 기존 세션을 반환 , 없으면 null이 반환 )
		HttpSession session = request.getSession(false);
		if (session != null) {
			out.println("SessionId:" + session.getId() + "<br><br>");
			out.println(getServletName() + "이 세션에서 nick 정보 반환<br><br>");
			out.println("닉네임:" + session.getAttribute("nick"));
		} else {
			out.println(getServletName() + " 세션이 없습니다<br><br>");
		}
		out.println("<br><br><a href=SessionOne>SessionOne으로 이동</a>");
		out.println("<br><br><a href=SessionThree>SessionThree로 이동</a>");
		out.close();
	}

}
package step5;

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

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;

/**
 * Servlet implementation class SessionThree
 */
@WebServlet("/SessionThree")
public class SessionThree extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SessionThree() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		// 세션을 반환받는다 ( 기존 세션이 있으면 기존 세션을 반환 , 없으면 null이 반환 )
		HttpSession session = request.getSession(false);
		if (session != null) {
			session.invalidate();// 로그아웃시 사용
			out.println(getServletName() + " 세션 invalidate 처리(무효화)<br><br>");
		} else {
			out.println(getServletName() + " 세션이 없습니다<br><br>");
		}
		out.println("<br><br><a href=SessionOne>SessionOne으로 이동</a>");
		out.println("<br><br><a href=SessionTwo>SessionTwo로 이동</a>");
		out.close();
	}
}


참고 ) 브라우저 캐시 : 웹페이지의 신속한 렌더링이 목적
 렌더링이란 HTML,Javascript,CSS 등의 웹문서를 브라우저에서 화면 형태로 출력하는 과정 
 캐시는 웹페이지의 요소 ( 이미지, CSS/JS , 오디오 비디오 ) 를 저장하기 위한 브라우저의 임시 저장소 
 

반응형

'[IT] > Servlet' 카테고리의 다른 글

Servlet.웹어플리케이션 실행 순서  (0) 2021.04.07
Servlet.WAS  (0) 2021.04.07
Servlet.Meta data  (0) 2021.04.07
Servlet.Servlet Annotation  (0) 2021.04.07
Servlet.ServletContextListener  (0) 2021.04.07
Servlet.ServletConfig/ServletContext  (0) 2021.04.06
Servlet.LifeCycle  (0) 2021.04.05
Servlet.get/post  (0) 2021.04.02
Comments