IT story/JSP

[Jsp 강의] L08Session

jason719 2016. 10. 27. 18:20

L08Session

Session에 대해 알아보자

아래와 같은 구조로 file을 생성한다.




index.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Session을 알아보자</title>
</head>
<body>
    <h1>Session 수업</h1>
    <h3><a href="./L01SetSession.jsp">Session Setting</a></h3>
    <h3><a href="./L02GetSession.jsp">Session 값 얻어오기</a></h3>
    <h3><a href="./L03GetSessions.jsp">Session 모든 값 얻어오기</a></h3>
    <h3><a href="./L04InfoSession.jsp">Session 정보</a></h3>
    <h3><a href="./L05RemoveSession.jsp">Session 삭제</a></h3>
    <h3><a href="./login/L01LoginForm.jsp">Session을 이용해 로그인 하기</a></h3>
</body>
</html>
cs

L01SetSession.jsp에서 Session Setting 하기

예제 1. L01SetSession.jsp 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Session Setting</title>
</head>
<body>
    <h1>세션 설정</h1>
    <%
        //HttpSession session = request.getSession(false); // 생략되어 있다.
        session.setAttribute("id""jsp");
        session.setAttribute("pwd"1234);
        session.setAttribute("name""kjs");
        out.print("<h3>설정완료</h3>");
    %>
    <p><a href="javascript:history.go(-1)">뒤로</a></p>
</body>
</html>
cs


L02GetSession.jsp에서 Session 값 얻어오기

예제 2. L02GetSession.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Session 값 얻어오기</title>
</head>
<body>
    <h1>세션 값</h1>
    <%--세션은 브라우저가 종료될 때까지 유지된다. --%>
    <h3>id : <%=session.getAttribute("id") %></h3>
    <h3>pw : <%=session.getAttribute("pwd") %></h3>
    <h3>name : <%=session.getAttribute("name") %></h3>
    <p><a href="javascript:history.go(-1)">뒤로가기</a></p>
</body>
</html>
cs


L03GetSessions.jsp에서 Session의 모든 값 얻어오기

예제 3. L03GetSessions.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
<%@page import="java.util.Enumeration"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Session 모든 값 얻어오기</title>
</head>
<body>
    <h1>세션에 설정된 모든 값</h1>
    <%
        Enumeration<String> names = session.getAttributeNames();
        //key값들을 받아오는 함수
        while(names.hasMoreElements()){
            String name = names.nextElement().toString();
    %>    
        <h3><%=name%> : <%=session.getAttribute(name)%></h3>
    <%    
        }            
    %>
    <p><a href="javascript:history.go(-1)">뒤로가기</a></p>
    
</body>
</html>
cs


L04InfoSession.jsp에서 Session 정보 확인하기

예제 4. L04InfoSession.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
35
36
37
38
39
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Session이 가진 정보를 보자</title>
</head>
<body>
    <h1>Session Information</h1>
    <h3>1. Session ID: <%=session.getId() %></h3>
    <%-- 서버가 브라우저(클라이언트)를 구분하기 위해 붙이는 고유ID 
    클라이언트가 서버에 접속하면 바로 생성
    서버가 종료될 때까지 or 강제로 만료시킬 때까지 유지되는 ID--%>
    <h3>2. Session 생성 여부: <%=session.isNew() %></h3>
    <%-- 클라이언트가 서버에 접속하면 최초 접속시 Session이 생성되는데
    이때 생성되면 true를 반환, 
    Session은 page에 생서되는 것이 아니라 프로젝트 기준으로 생성
    프로젝트 내부에서는 Session이 공유 됨--%>
    <%
    /*
        전체 세션 만료시간 설정
        web.xml에 session-timeout 지정하기
        <session-config>
            <session-timeout>분</session-timeout> 지정하기
        </session-config>
    */
    //특정 세션 만료시간 설정 (분*60)
    session.setMaxInactiveInterval(5*60);
    long lastTime = session.getLastAccessedTime();
    long createTime = session.getCreationTime();
    long usedTime = (lastTime - createTime)/60000;//분
    long inactive = session.getMaxInactiveInterval()/60;//분
    %>
    <h3>3. Session 유효 시간: <%=inactive %></h3>
    <%--페이지를 방문한 시점으로부터 유효시간이기 때문에 30분이 바뀌지 않는다. --%>
    <h3>4. 웹사이트에 머문 시간: <%=usedTime %></h3>
</body>
</html>
cs


L05RemoveSession.jsp에서 Session 삭제하기

예제 5. L05RemoveSession.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Session의 값을 삭제하자</title>
</head>
<body>
    <h1>세션 특정 값 삭제</h1>
    <%session.removeAttribute("id"); //세션에서 특정 데이터를 제거합니다.%>
    <h3>id : <%=session.getAttribute("id") %></h3>
    <h3>pwd : <%=session.getAttribute("pwd") %></h3>
    <h3>name : <%=session.getAttribute("name") %></h3>
    
    <h1>전체 세션 만료</h1>
    <%session.invalidate(); //세션의 모든 데이터를 삭제합니다. %>
    <%-- session 객체 자체를 null로 만들기 때문에 오류가 발생 --%>
</body>
</html>
cs


login/L01LoginForm.jsp에서 Session을 이용해 로그인 하기

예제 6./login/L01LoginForm.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
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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>servlet을 이용해서 로그인을 성공하자</title>
</head>
<body>
    <h1>로그인 form</h1>
    <%-- 제출한 파라미터와 db에서 가져온 id와 pw를 L02LoginController.java에서 검사 
        같으면 login 세션을 생성 후 1대입 id 세션 생성, 다르면 0대입
        login 실패시 login 세션 생성후 0대입
        
        이때 L03LoginResult.jsp redirect 방식으로 이동해라.
        id는 세션으로 출력
        
        L03LoginResult.jsp에서 세션 login이 없거나 0이면 접근할 수 없도록해라
        (강제로 L01LoginForm.jsp)로 이동
         
        L03LoginResult.jsp에 로그아웃 버튼 -> L04Logout.java(/logout)
        ->로그아웃 성공시 L01LoginForm.jsp로 이동
    --%>
    <%
        String msg = request.getParameter("msg");
        if(msg != null){
    %>
            <h3 style="color: red"><%=msg %></h3>
    <%
        }
    %>
    
    <%     Object login = session.getAttribute("login");
        if(login != null){
            if((int)login == 0){
    %>
        <h3 style="color: red">아이디 or 패스워드를 잘못 입력했습니다.</h3>
    <%    
        session.removeAttribute("login");
        login = null;
            }else if((int)login == 1){ %>
            <h3><%=session.getAttribute("id") %>님 로그아웃 하시겠습니까?</h3>
            <h4><a href="./../logout">로그아웃</a></h4>
    <%        }
        }
    %>
    
    
    <%
    if(login == null){%>
    
    <form action="./../loginCtrl" method="post">
        <p>
            <label>아이디:</label>
            <input type="text" name="id" value="">
        </p>
        <p>
            <label>비밀번호:</label>
            <input type="password" name="pwd" value="">
        </p>
        <button type="submit">제출</button>&nbsp;&nbsp;&nbsp;<a href="./../index.jsp">홈으로</a>
    </form>
        <br />
        
    <%} 
    %>
    
</body>
</html>
cs


예제 7. L02SignupController.java

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
package com.jsp.controller;
 
import java.io.IOException;
 
import javax.servlet.RequestDispatcher;
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;
import javax.websocket.Session;
 
 
@WebServlet("/loginCtrl")
public class L02SignupController extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
    }
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String db_id = "jsp";
        String db_pwd= "1234";
        
        
        response.setContentType("text/html; charset=utf-8");
        String id = request.getParameter("id");
        String pwd = request.getParameter("pwd");
        System.out.println("id: "+id+" //pwd: "+pwd);
        HttpSession session = request.getSession(false);
        if(id.equals(db_id) && pwd.equals(db_pwd)){
            session.setAttribute("login"1); //Object type으로 넘어온다
            session.setAttribute("id", id);
            response.sendRedirect("./login/L03LoginResult.jsp");
            //login이 1이면 true, 0이면 false
 
        }else{
            session.setAttribute("login"0);
            response.sendRedirect("./login/L01LoginForm.jsp");
        }
    }
 
}
 
cs


예제 8. /login/L03LoginResult.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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>login 성공 페이지</title>
</head>
<body>
    <%-- parameter login이 오지 않으면 이 페이지에 접근할 수 없다.
          이때 login은 세션 또는 쿠키 대신이다.
          세션 or 쿠키는 브라우저가 유지하고 있는 파라미터이다. --%>
          <%
          //Object는 모든 class의 부모이기 때문에 casting으로 형변환 가능
          Object login = session.getAttribute("login");
          boolean access = false;
          if(login != null){
              if((int)login == 1){
                  access = true;
              }
              
          }
          if(!access){
              response.sendRedirect("./login/L01LoginForm.jsp?msg=access failed");
          }
          %>
    <h1><%=session.getAttribute("id") %>로그인 성공 페이지</h1>
    <a href="./../index.jsp">홈으로</a>
    <a href="./../logout">로그아웃</a>
</body>
</html>
cs


예제 9. L04Logout.java

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
package com.jsp.controller;
 
import java.io.IOException;
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("/logout")
public class L04Logout extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        session.invalidate();
        response.sendRedirect("./login/L01LoginForm.jsp?msg=logout success");
    }
 
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
    }
 
}
 
cs


'IT story > JSP' 카테고리의 다른 글

[Jsp 강의] L10Bean  (0) 2016.10.27
[Jsp 강의] L09Cookie  (0) 2016.10.27
[Jsp 강의] L07Template  (0) 2016.10.27
[Jsp 강의] L06Forward  (0) 2016.10.27
[Jsp 강의] L05Redirect  (0) 2016.10.27