Session : Cookie 와 유사한 동작을 하나, 별도의 동작을 하는 객체
![]() |
| 세션 객체 생성 및 전달 과정 |
- session 객체는 브라우저가 종료되기 전까지만 생존함
- client pc 가 아닌 server 에 저장됨
![]() |
| cookie와 session의 차이 |
※session 의 타입
cookie 는 기본적으로 text 타입이었기에, 문자열에서 원하는 타입으로 변환함수를 사용하여 사용 했었다.
반면, session 의 경우 'Object'타입, 모든 타입의 슈퍼 클래스(부모 클래스)이다.
따라서, 형 변환 함수가 아닌, 다운 캐스팅으로 원하는 타입에 맞춰야 한다.
※session 객체 생성 및 호출
JSP 파일 일 때,
Seesion 객체 name 생성 : session.setAttribute("name 명",value)
Session 객체 name 호출 : session.getAttribute("name 명")
Session 객체 name 삭제 : session.removeAttribute("name 명");
Servlet 파일 일 때,
HttpSession session = request.getSession();
-> 별도로 sessino 객체 자체를 생성해야 함
※ 이후 과정은 JSP 와 동일
Session 을 이용한 로그인 재현 실습
※로그인 전 ex10main.jsp
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 | <%@ 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> </head> <body> <!-- 로그인 여부에 따라 페이지에 출력되는 값이 달라짐 --> <% String id = (String)session.getAttribute("id"); if(id!= null){%> <h1><%=id+"님"%></h1><br> 로그인 중입니다<br> <a href="ex10_logout">로그아웃하기</a> <!-- 캐시 삭제 방법 1. 브라우저 전부 닫기 2. tomcat server 정지 -> session 값은 server에서 보관중 --> <%}else{%> <h1>로그인</h1> <form action="ex10_login.jsp" method = "POST"> ID : <input type="text" name = "id"><br> PW : <input type="text" name = "pw"><br> <input type="submit" value ="로그인"> </form> <%}%> </body> </html> | cs |
※로그인 실패 시 페이지 ex10_loginF.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <%@ 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> </head> <body> <h1>로그인 실패!</h1> <p>아이디나 비밀번호를 확인해주세요.</p> <a href="ex10_main.jsp">로그인 페이지로</a> </body> </html | cs |
※로그인 성공 여부에 대해 별도로 처리할 필요가 있음
->ex10_login.jsp
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 | <%@ 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> </head> <body> <% //입력받은 값을 전달 받음 String id = request.getParameter("id"); String pw = request.getParameter("pw"); String nextPage = ""; //로그인 성공여부에따라 페이지 이동이 달라짐 if(id.equals("smhrd")&&pw.equals("12345")){ nextPage = "ex10_main.jsp"; session.setAttribute("id", id); } else nextPage = "ex10_loginF.jsp"; response.sendRedirect(nextPage); %> </body> </html> | cs |



댓글
댓글 쓰기