Cookie and Session

12173 단어 SpringSpring

Cookie and Session

HTTP 프로토콜 방식으로 통신하는 웹페이지들은 서로 어떠한 정보도 공유하고 있지 않기때문에
상태나 정보를 공유하라면 세션 트래킹이라는 웹페이지 연결기능을 구현해야한다

1. hidden 태그 : hidden 태그 사용

<input type="hidden" name="user_address" value="서울시 성북구" />
<input type="hidden" name="user_email" value="[email protected]" />
<input type="hidden" name="user_hp" value="010-111-2222" />

2. URL Rewriting : get 방식으로 url 뒤에 붙여서 사용

user_address = URLEncoder.encode(user_address, "utf-8");
out.print("<a href='/pro09/second?user_id=" + user_id 
			                    + "&user_pw=" + user_pw 
			                    + "&user_address=" + user_address
			                    + "'>두 번째 서블릿으로 보내기</a>");

3. Cookie 사용

쿠키란 웹페이지에서의 공유정보를 클라이언트 PC에 저장해두고 필요할때 여러 웹 페이지들이
고융해서 사용할수있도록 하는 방법.

  • 정보가 클라이언트 PC에 저장
  • 저장 용량에 제한이 있다
  • 보안이 취약
  • 클라이언트 브라우저에서 사용 유무 설정 가능
  • 도메인당 쿠키가 만들어진다

Cookie는 Persistence 쿠키, Session 쿠키로 나뉘는데
Persistence 쿠키는
파일로 생성되며, 쿠키를 삭제하거나 쿠키설정값이 종료되었을때 종료된다.
또한 최초접속시에 서버로 전송되고, 로그인 유무와 팝업창을 제한할때 사용된다
Session 쿠키는
브라우저 메모리에 생성되고 브라우저를 종료햇을때 함께 종료된다.
최초접속시에는 서버로 전송되지않고, 사이트접속했을때에 Session 인증정보를 유지할때 사용된다

Servlet에서 쿠키 사용

파일저장 방식
//set
Date d = new Date();
//Cookie 객체를 생성한후 한글 정보를 인코딩해서 쿠키에 저장
Cookie c = new Cookie("cookieTest", URLEncoder.encode("what프로그래밍입니다.", "utf-8"));
//유효 기간을 설정
c.setMaxAge(24*60*60);
//생성된 쿠키 브라우저도 전송
response.addCookie(c);
//get
Cookie[] allValues = request.getCookies();
for(int i=0; i<allValues.length;i++){
 if(allValues[i].getName().equals("cookieTest")){
   out.println("<h2>Cookie 값 가져오기 : " + URLDecoder.decode(allValues[i].getValue(), "utf-8"));
   }
}
세션쿠키

setMaxAge(a)의 a값을 음수로 만들어주면 Session Cookie로 만들어진다

//set
Date d = new Date();
//Cookie 객체를 생성한후 한글 정보를 인코딩해서 쿠키에 저장
Cookie c = new Cookie("cookieTest", URLEncoder.encode("what프로그래밍입니다.", "utf-8"));
//유효 기간을 설정
c.setMaxAge(-1);
//생성된 쿠키 브라우저도 전송
response.addCookie(c);

세션을 이용한 웹페이지 연동

쿠키는 사용시 웹페이지들의 정보가 클라이언트 PC에 저장되므로 정보가 쉽게 노출될수있는 반면,
세션은 서버의 메모리에 생성되어 정보를 저장한다. 이처럼 보안이 요구되는 정보는 대부분 세션을 사용하게된다. 또한 세션은 각 브라우저당 한개 즉 사용자당 한개가 생성된다.

  • 정보가 서버의 메모리에 저장
  • 브라우저의 세션 연동은 세션 쿠키 사용
  • 쿠키보다 보안 유리
  • 서버에 부하를 줄수있음
  • 세션은 유효시간을 가진다

클라이언트가 처음 서버에 접속했을때에 서버는 세션 객체를 생성하고 세션 객체에 대한 세션 ID를 브라우저에 전송시켜주고 브라우저는 이 세션 ID를 세션 쿠키에 저장시킨다.
재접속햇을때에 서버에서는 이 세션 쿠키를 가지고 세션 객체에 접근하여 브라우저에 대한 작업을 수행하게된다.

HttpSession session = request.getSession();
out.println("세션 아이디 : " + session.getId() + "<br>");
out.println("최초 세션 생성 시각  : " + new Date(session.getCreationTime()) + "<br>");
out.println("최초 세션 접근 시각  : " + new Date(session.getLastAccessedTime()) + "<br>");
out.println("세션 유효 시간  : " + session.getMaxInactiveInterval() + "<br>");
if(session.isNew()){
	out.print("새 새션이 만들어졌습니다.");
}

//세션 유효시간 설정
session.setMaxInactiveInterval(5);
//세션 강제 삭제
session.invalidate();

세션 쿠키 확인 방법

쿠키를 사용할수 없을때
쿠키를 사용할수 없을경우네는 encodeURL() 메서드를 이용해서 세션 기능을 사용할수있다.

String url = response.encodeURL("login");
out.println("<a href="+url+">로그인 상태 확인 </a>");

세션 이용 로그인 예제

//LoginServlet
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doHandle(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doHandle(request, response);
	}

	private void doHandle(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		String user_id = request.getParameter("user_id");
		String user_pwd = request.getParameter("user_pwd");
		//VO 객체 생성 및 속성에 값 설정 해주기
		MemberVO memberVO = new MemberVO();
		memberVO.setId(user_id);
		memberVO.setPwd(user_pwd);
		System.out.println("memberVO : "+ memberVO);
		MemberDAO dao = new MemberDAO();
		//memberVO를 dao에 전달
		boolean result = dao.isExisted(memberVO);
		if(result){
			HttpSession session = request.getSession();
			session.setAttribute("isLogon", true);
			session.setAttribute("login.id", user_id);
			session.setAttribute("login.pwd", user_pwd);
			out.print("<html><body>");
			out.print("안녕하세요  " + user_id + "님!!!<br>");
			out.print("<a href='show'>회원정보 보기</a>");
			out.print("</body></html>");
		}else{
			out.print("<html><body><center>회원 아이디가 틀립니다.");
			out.print("<a href='login3.html'>다시 로그인 하기 </a>");
			out.print("</body></html>");
		}
	}
}

//MemberDAO
....
public boolean isExisted(MemberVO memberVO) {
	boolean result = false;
	String id = memberVO.getId();
	String pwd = memberVO.getPwd();
	try{
		con = dataFactory.getConnection();
		String query = "select decode(count(*),1,'true','fase') as result from t_member";
		query += " where id=? and pwd=?";
		pstmt = con.prepareStatement(query);
		pstmt.setString(1, id);
		pstmt.setString(2, pwd);
		ResultSet rs = pstmt.executeQuery();
		rs.next();
		result = Boolean.parseBoolean(rs.getString("result"));
		System.out.println("rsult =" + result);
	}catch(Exception e){
		e.printStackTrace();
	}
	return result;
}

좋은 웹페이지 즐겨찾기