본문 바로가기

개발/JSP

[JSP] 쿠키와 세션 정리








쿠키는 클라이언트(사용자 컴퓨터)에 저장되고, 세션은 서버에 저장된다.






      [ 쿠키와 관련된 작업 ]


 

 

   
새로운 쿠키를 만들어서 추가하는 방법 


 

 

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<%@ page import="java.net.*" %>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>쿠키생성</title>

</head>

<body>

 

<%

      Cookie cookie = new Cookie("temp","3");

      response.addCookie(cookie);

     

      Cookie cookie1 = new Cookie("test","5");

      response.addCookie(cookie1);

     

      Cookie cookie2 = new Cookie("jiwon","babo");

      response.addCookie(cookie2);

     

      Cookie cookie3 = new Cookie("hwasup","babo anim");

      response.addCookie(cookie3);

%>

 

</body>

</html>





     만들어진 쿠키의 값 읽어오기




[ request객체의 getCookies() 메소드를 사용하면 클라이언트에 설정된

모든 쿠키 객체들을 얻어올 수 있다. ]

 

 

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>쿠키 조회</title>

</head>

<body>

 

<%

Cookie[] cookies = request.getCookies(); //쿠키 목록 받아오기

       for(Cookie cookie: cookies) {

     

          //모든 쿠키의 이름과 출력

          System.out.println(cookie.getName()+":"+cookie.getValue());

             

      }

%>   

</body>

</html>






   
이미 있는 쿠키의 값을 변경하는 방법



 

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>쿠키 변경</title>

</head>

<body>

 

<%

      Cookie[] cookies = request.getCookies();  //cookie 목록 가져오기.

      for(Cookie cookie : cookies) {

 

if(cookie.getName().equals("jiwon")){  //cookie이름이 "jiwon" 같으면

 

            cookie.setValue("beautiful");      //cookie값을 "beautiful" 변경해준다.

            response.addCookie(cookie);      // 쿠키 값을 *업데이트* 해준다.

                 

                  System.out.println(cookie);

            }

      }

%>     

</body>

</html>





     쿠키를 제거하는 방법

 

 

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>쿠키 삭제하기</title>

</head>

<body>

 

  <!-- 값이 5 쿠키 삭제 -->

<%

  Cookie[] cookies = request.getCookies();

 

  for(Cookie cookie : cookies) {

  if(cookie.getValue().equals("5")){

             cookie.setMaxAge(0);

         response.addCookie(cookie);

       }

  }

 

%>   

   

</body>

</html>






[ 세션과 관련된 작업 ]

 

 



       세션을 만들어서 추가하는 방법


 


 

[ JSP에서는 세션 객체가 내장되어 있어 바로 사용할 수 있지만, 서블릿에서 세션을 다루려면

  doGet, doPost 메소드의 매개변수인 HttpServletRequest getSession() 메소드를 호출해야 한다. ]

 

 



      세션에 새로운 데이터를 넣는 방법 



protected void doPost(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException {

 

            HttpSession session = request.getSession();

           

            session.setAttribute("login", request.getParameter("userid"));

            session.setAttribute("answer", new ArrayList<String>());

           

            response.sendRedirect("quiz");

      }




      세션에서 값을 꺼내는 방법

 

                 req.getSession().getAttribute("");





       세션을 무효과 시키는 방법


 Session.invalidate();