JSP

[JSP] 세션

반응형

[JSP] 세션(session)


세션이란?

세션도 쿠키와 마찬가지로 서버와의 관계를 유지하기 위한 수단

하지만, 세션은 쿠키와 달리 클라이언트의 특정 위치에 저장되는 것이 아니라 '서버 상에 객체로 존재'

따라서 세션은 서버에서만 접근이 가능하기 때문에 보안이 좋고, 저장할 수 있는 데이터 한계 없음




  1. 클라이언트 요청 (웹 브라우저)

  2. session 자동 생성

  3. Session 속성 설정 (session 내부 객체의 메소드 이용)




세션을 이용한 간단한 로그인 페이지 만들기


login.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
 
    <form action="loginOk.jsp" method="post">
        아이디 : <input type="text" name="id" size="10"><br/>
        비밀번호 : <input type="password" name="pw" size="10"><br/>
        <input type="submit" value="로그인">
    </form>
    
</body>
</html>
cs

로그인하면, action을 통해 loginOk.jsp로 post형태로 전송된다.




loginOk.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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!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=EUC-KR">
<title>Insert title here</title>
</head>
<body>
    <%!
        String id, pw;
    %>
    
    <%
        id = request.getParameter("id");
        pw = request.getParameter("pw");
        
        if(id.equals("abcde"&& pw.equals("12345")){ // 아이디가 abcde, 비밀번호 12345일 때
            session.setAttribute("id", id); // 세션에 id 값 저장
            response.sendRedirect("welcome.jsp");
        } else {
            response.sendRedirect("login.html");
        }
    %>
</body>
</html>
cs

미리 지정한 id가 abcde고, pw가 12345일 때 세션에 id 값을 저장하는 모습을 볼 수 있다.

맞으면 welcome.jsp로, 틀리면 다시 login.html로 가는 if문으로 이루어져 있다.





welcome.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
<%@ page import = "java.util.Enumeration" %>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!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=EUC-KR">
<title>Insert title here</title>
</head>
<body>
 
    <%
        Enumeration enumeration = session.getAttributeNames();
        while(enumeration.hasMoreElements()){
            String sName = enumeration.nextElement().toString();
            String sValue = (String)session.getAttribute(sName);
            
            if(sValue.equals("abcde"))
                out.println(sValue + "님 안녕하세요." + "<br/>");
        }
    %>
    
    <a href="logout.jsp">로그아웃</a>
 
</body>
</html>
cs

session의 getAttributeNames()를 이용하면, 저장된 속성의 모든 정보를 가져올 수 있다. 이를 enumeration을 이용해 저장한다. (지시자를 import해야하는 것 확인)

String변수에 이름과 값을 저장시키고, 값이 abcde일 때 로그인에 성공했다는 출력문을 나타낸다.

이곳은 로그인 완료 화면이기 때문에 하이퍼링크로 logout.jsp를 나타내고 로그아웃도 구현할 수 있다.







logout.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=EUC-KR"
    pageEncoding="EUC-KR"%>
<!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=EUC-KR">
<title>Insert title here</title>
</head>
<body>
 
    <%
        Enumeration enumeration = session.getAttributeNames();
        while(enumeration.hasMoreElements()){
            String sName = enumeration.nextElement().toString();
            String sValue = (String)session.getAttribute(sName);
            
            if(sValue.equals("abcde")){
                session.removeAttribute(sName);
                response.sendRedirect("login.html");
            }
        }
    %>
</body>
</html>
cs


logout에서는, sValue 값이 abcde일 때 session.removeAttribute 메소드를 통해 해당 세션 값을 지워준다.

그리고 다시 response를 통해 login.html로 보내준다.




앞으로 세션을 이용해서 값을 저장하는 일이 많기 때문에 진행과정에 대해서 잘 알고 넘어가자



반응형

'JSP' 카테고리의 다른 글

[JSP] 자바 빈(Bean)  (0) 2018.05.11
[JSP] 예외 페이지  (0) 2018.05.11
[JSP] 쿠키  (0) 2018.05.09
[JSP] 액션 태그  (0) 2018.05.09
[JSP] JSP 기본 정리  (0) 2018.05.09