Cohe

3. Cookie, Session 본문

개발 언어/JSP

3. Cookie, Session

코헤0121 2024. 4. 8. 17:19
728x90
  1. 퀴즈
    • <a href="req_quiz02_ok2.jsp?num=<%=i%>"><%=i%>번 학생</a><br> 여기서 ?으로 구분값이 있다.
    • 변수는 <%= 으로 넣기!
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="EUC-KR">
    <title>Request quiz02 Okay</title>
    </head>
    <body>
    
    <p>다음을 구현하고 a 태그 클릭시 req_quiz02_ok에 학생번호를 출력하시오</p>
    <% for (int i =1;i<=30;i++){%>
    	<a href="req_quiz02_ok2.jsp?num=<%=i%>"><%=i%>번 학생</a><br>
    	<%}
    %>
    
    </body>
    </html>
    
  2. redirect 페이지를 이동시키겠다 → sendredirect를 사용하면 된다.
    • <td rowspan="2"><input type="submit" value="로그인" class ="btn"></td></tr>
      • rowspan은 위 아래로 합친다!
      <%@ page language="java" contentType="text/html; charset=EUC-KR"
          pageEncoding="EUC-KR"%>
          <%
          //controller의 역할을 한다
          
          /*
          login.jsp 페이지로부터 넘어온 id, pw를 받아 처리
          id가 abc1234이고 pw가 asd123이면 로그인 성공이라고 간주
          if id&pw {login_welcome page로 리다이렉트}
          if !id {login_id_fail.jsp 로 리다이렉트}
          if !pw (login_pw_fail.jsp 로 리다리렉트)
          */ 
          
          String id = request.getParameter("id");
          String pw = request.getParameter("pw");
          
          if(id.equals("abc1234")){
          	if(pw.equals("asd123")){
          		response.sendRedirect("login_welcome.jsp");
          	}
          	else{
          		//패스워드 오류
          		response.sendRedirect("login_pw_fail.jsp");
          	}
          }
          else{
      		response.sendRedirect("login_id_fail.jsp");
          }
          
          %>
      
    1. 나이를 입력받아서 성인인지 미자인지 확인하기
      • 그 입력 나이에 따라서 20살 이상이면 성년입니다를 출력하는 페이지로 이동, 20살 미만이면 미성년입니다를 출력하는 페이지로 이동
      • code
        • 더보기
          <%@ page language="java" contentType="text/html; charset=EUC-KR"
              pageEncoding="EUC-KR"%>
          <!DOCTYPE html>
          <html>
          <head>
          <meta charset="EUC-KR">
          <title>res_ex01</title>
          </head>
          <body>

          <h2>res_ex01</h2>
          <form action="res_ex01_result.jsp">
          <input type="text" name ="age">
          <input type="submit">
          </form>
          </body>
          </html>
        • 더보기
          <%@ page language="java" contentType="text/html; charset=EUC-KR"
              pageEncoding="EUC-KR"%>
              
              
           <% 

            String ageParam = request.getParameter("age");
            int age;
            age = Integer.parseInt(ageParam);
           
            if(age>=20){
               response.sendRedirect("res_ex01_ok.jsp");
              
              }
              else{
          response.sendRedirect("res_ex01_no.jsp");
              }
              
              %>
        • 더보기
          <%@ page language="java" contentType="text/html; charset=EUC-KR"
              pageEncoding="EUC-KR"%>
          <!DOCTYPE html>
          <html>
          <head>
          <meta charset="EUC-KR">
          <title>Insert title here</title>
          </head>
          <body>
          <div align="center">
          <h2>미성년입니다</h2>
          </div>
          </body>
          </html>
        • 더보기
          <%@ page language="java" contentType="text/html; charset=EUC-KR"
              pageEncoding="EUC-KR"%>
          <!DOCTYPE html>
          <html>
          <head>
          <meta charset="EUC-KR">
          <title>Insert title here</title>
          </head>
          <body>
          <div align="center">
          <h2>성년입니다</h2>
          </div>
          </body>
          </html>
  3. out 객체
    • jsp 페이지가 생성하는 모든 내용은 out기본객체 (print.write부분)를 통해 전송됩니다.
    • 표현식으로 대체할 수 있다 → 쳐야하는 내용이 많아서 대체하지 않는다.
    • 예시 코드
      • 더보기
        <%@ page language="java" contentType="text/html; charset=EUC-KR"
            pageEncoding="EUC-KR"%>
        <!DOCTYPE html>
        <html>
        <head>
        <meta charset="EUC-KR">
        <title>outExample.jsp</title>
        </head>
        <body>

        <h2>out 객체</h2>
        <p>
        out 객체는 jsp에서 html로 보내기위한 출력 객체를 말함 표현식이 이를 대체하고 있음.
        </p>

        <%
        for(int i =1;i<=10;i++){
        out.println("<input type='checkbox' name ='check'>"+i);

        }
        %>
        <br>
        <%
        for(int i = 1;i<=10;i++){%>
        <input type="checkbox" name = 'check'><%=i %>

        <%}%>

        </body>
        </html>

내장객체의 종류

  • request, response, out
  • session, application

Session

  • 특정정보를 전달할 때 필요한 정보를 유지해야 한다. → 이를 위해서 쿠키와 세션을 사용한다.
    • 쿠키 : 서버가 아닌 클라이언트 측에 정보를 저장한다. 서버에게 정보를 요청한다. 쿠키는 개당 4kbyte를 넘길 수 없다.
      • 내장 객체가 아니다. 직접 만들어야 한다.
      1. 쿠키 클래스 만든다
      2. setter 메서드로 쿠키의 속성을 설정
      3. response 객체에 쿠키 탑재
      4. 로컬 환경에 저장
      • console.log(document.cookie);
      • 쿠키 생성 방법
        1. 쿠키 객체 생성 : 생성-생성자 매개변수로 (쿠키 이름, 쿠키 값) <내장 객체는 사용자가 객체 생성을 안하더라도 객체가 생성된다. 즉 cookie는 내장 객체가 아니다.>
        2. 쿠키 유효 시간 설정
        3. 응답 객체에 쿠키 탑재 ⇒ 클라이언트가 응답 내용을 받을 때 해당 내용을 가져가게 된다.
      • 쿠키 사용하기
        • code
          • 더보기
            <%@ page language="java" contentType="text/html; charset=EUC-KR"
                pageEncoding="EUC-KR"%>
            <%
            Cookie idCoo = new Cookie("user_id","kkk123");
            Cookie nameCoo = new Cookie("user_name", "홍길동");

            //2. 쿠키 시간 설정
            idCoo.setMaxAge(60*60); //한 시간
            nameCoo.setMaxAge(20); //20초

            //3. 응답 객체에 쿠키 탑재 ⇒ 클라이언트가 응답 내용을 받을 때 해당 내용을 가져가게 된다.
            response.addCookie(idCoo);
            response.addCookie(nameCoo);
            %>

            <!DOCTYPE html>
            <html>
            <head>
            <meta charset="EUC-KR">
            <title>Insert title here</title>
            </head>
            <body>
            <a href="cookie_get.jsp">쿠키 확인하기</a>
            </body>
            </html>
          • 더보기
            <%@ page language="java" contentType="text/html; charset=EUC-KR"
                pageEncoding="EUC-KR"%>
                
            <%
            //쿠키 사용하기
            //쿠키는 요청 시 자동으로 전송되고, request에 자동으로 저장됩니다.
            Cookie[] cArr = request.getCookies(); //쿠키 배열로 받음
            if(cArr!=null){
            //cookie is not null, then run
            for(int i =0;i<cArr.length;i++){
            out.println(cArr[i].getName()+" : ");//cookie's name
            out.println(cArr[i].getValue()+"<br>");
            }

            }
            %>
            <!DOCTYPE html>
            <html>
            <head>
            <meta charset="EUC-KR">
            <title>cookie_get.jsp</title>
            </head>
            <body>

            </body>
            </html>
    • 쿠키 문제
      1. date 클래스를 이용하여 이 페이지에 접근한 시간을 xxx년 xx월 xx 일 형태로 생성, 날짜 형식을 문자열 형태로 show라는 이름의 쿠키로 생성
        • 쿠키에 저장된 값 확인해보기 <a href=”cookie02.jsp”></a>
          • 더보기
            <%@page import="java.text.SimpleDateFormat"%>
            <%@ page language="java" contentType="text/html; charset=EUC-KR"
                pageEncoding="EUC-KR"%>
                
            <%@ page import="java.time.LocalDateTime, java.time.ZoneId" %>
            <%@ page import="java.util.Date" %>
            <%@ page import="java.text.SimpleDateFormat" %>
            <%


            // date와 lt 변수가 어디서 가져오는지 명확하지 않으므로, 임의의 값으로 대체합니다.
            // 예를 들어, 현재 날짜와 시간을 사용하려면 다음과 같이 할 수 있습니다.

            Date now = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            //LocalDateTime localDateTimeNow = LocalDateTime.now();

            // Cookie 값으로는 문자열을 사용해야 합니다.
            Cookie show = new Cookie("show", sdf.format(now));

            // 쿠키 시간 설정
            show.setMaxAge(30); // 1시간

            // 응답 객체에 쿠키 추가
            response.addCookie(show);
            %>
            <!DOCTYPE html>
            <html>
            <head>
            <meta charset="EUC-KR">
            <title>Insert title here</title>
            </head>
            <body>

            <a href="cookie02.jsp">쿠키에 저장된 값 확인해보기</a>
            </body>
            </html>
      2. cookie02.jsp
        • show 쿠키가 있다면 쿠키가 가지고 있는 값을 화면에 출력 만약 없다면 쿠키가 없습니다 출력
          • 더보기
            <%@ page language="java" contentType="text/html; charset=EUC-KR"
                pageEncoding="EUC-KR"%>

            <%
            //쿠키 사용하기
            //쿠키는 요청 시 자동으로 전송되고, request에 자동으로 저장됩니다.
            Cookie[] cArr = request.getCookies(); //쿠키 배열로 받음
            boolean flag = false;
            if(cArr!=null){
            //cookie is not null, then run
            for(int i =0;i<cArr.length;i++){
            if(cArr[i].getName().equals("show")){
            out.println(cArr[i].getValue()+"<br>");
            flag=true;
            }
            }
            }

            if(!flag){
            out.println("쿠키가 없습니다");
            }
            %>
            <!DOCTYPE html>

            <html>
            <head>
            <meta charset="EUC-KR">
            <title>Insert title here</title>
            </head>
            <body>

            </body>
            </html>
  • 세션
    • 서버 상의 객체 형태로 존재, session 객체는 브라우저 창이 종료되면 같이 없어진다. → 브라우저 별로 세션이 분리가 된다.
    • 세션은 클라이언트 요청 발생시 자동 생성된다. jsp session 하고 나온 것들이다! 세션id를 통해 구분을 한다.
    • 쿠키는 클라이언트에 저장되어 누구나 다 참조 가능하나 세션은 어떤 값이 참조되어있는지 알 수 없다.
      • 세션은 강제로 사용자가 쿠키를 차단한 경우에도 사용할 수 있다.
    • 세션에 저장된 값은 브라우저가 종료되기까지 또는 기본 시간 30분까지 어느 페이지에서나 사용이 가능하다
더보기

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>session_login.jsp</title>
</head>
<body>
<%

String id = (String)session.getAttribute("id"); //type casting 필요
String name = (String)session.getAttribute("user_name"); //type casting 필요
if(id==null){
%> 
<h2>세션 로그인</h2>
<form action="session_login_ok.jsp" method="post">
ID : <input type="text" name="id"><br>
PW : <input type="password" name="pw"><br>
NICK : <input type="text" name="nick"><br>
<input type="submit" name="login"><br>
</form>
<%
}
else{
response.sendRedirect("login_welcome.jsp");
}
%>

</body>
</html>

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
    
<%
	/*
	1. 아이디 비밀번호 닉네임 받기
	2. 조건 : 아이디와 비밀번호가 서로 동일하면 user_id 이름으로 id 세션에 저장, user_name 이름으로 nick 세션에 저장,
		session_welcome 페이지를 작성, 이동한 후에 "id님(name) 환영합니다."
		아이디와 비밀번호가 일치하지 않은 경우 다시 로그인 페이지로 리다이렉트
	*/
	request.setCharacterEncoding("utf-8");
	String id = request.getParameter("id"); // 아이디 받기
	String pw = request.getParameter("pw"); // 비밀번호 받기
	String nick = request.getParameter("nick"); // 비밀번호 받기
	
	if(id.equals(pw)){

		session.setAttribute("id", id);
		session.setAttribute("user_name",nick);
		response.sendRedirect("login_welcome.jsp");
	}
	else{

		response.sendRedirect("session_login.jsp");
	}

%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>session_login_ok.jsp</title>
</head>
<body>
	
</body>
</html>
더보기

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
    
    
    <%
    
    String id = (String)session.getAttribute("id"); //type casting 필요
    String name = (String)session.getAttribute("user_name"); //type casting 필요
    %>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<%
if(id!=null){
%> <h2><%=id %> (<%=name %>)님 반가워요!!</h2><%
}
else{
response.sendRedirect("session_login.jsp");
}
%>
<a href="logout.jsp">로그아웃</a>
</body>
</html>

 

더보기

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
    
    <%
    session.removeAttribute("id"); //인증처리하는 세션을 삭제, 로그인 할 때 만들어지는 것을 삭제
    session.invalidate();
    
    response.sendRedirect("session_login.jsp");
    %>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>

</body>
</html>

'개발 언어 > JSP' 카테고리의 다른 글

JSP mini project : mypage 실습  (0) 2024.04.15
6-1 JSP-JDBC 연동2  (0) 2024.04.12
6. JSP-JDBC 연동  (0) 2024.04.11
5. javaBean  (0) 2024.04.11
4. application, param, include, forward, action tag, error page  (0) 2024.04.09