본문 바로가기

프로그래밍/JAVA, Servlet, JSP

Cookie, Session <유용한 소스>

:::쿠키생성:::
<%@ page contentType = "text/html; charset=euc-kr" %>
<%@ page import! = "java.net.URLEncoder" %>
<%
    Cookie cookie = new Cookie("name", URLEncoder.encode("최범균"));
    response.addCookie(cookie);
%>
<html>
<head><title>쿠키생성</title></head>
<body>

<%= cookie.getName() %> 쿠키의 값 = "<%= cookie.getValue() %>"

</body>
</html>

 

:::쿠키 뷰:::
<%@ page contentType = "text/html; charset=euc-kr" %>
<%@ page import! = "java.net.URLDecoder" %>
<html>
<head><title>쿠키목록</title></head>
<body>
쿠키 목록<br>
<%
    Cookie[] cookies = request.getCookies();
    if (cookies != null && cookies.length > 0) {
        for (int i = 0 ; i < cookies.length ; i++) {
%>
    <%= cookies[i].getName() %> =
    <%= URLDecoder.decode(cookies[i].getValue()) %><br>
<%
        }
    } else {
%>
쿠키가 존재하지 않습니다.
<%
    }
%>
</body>
</html>

 


:::쿠키값 변경:::
<%@ page contentType = "text/html; charset=euc-kr" %>
<%@ page import! = "java.net.URLEncoder" %>
<%
    Cookie[] cookies = request.getCookies();
    if (cookies != null && cookies.length > 0) {
        for (int i = 0 ; i < cookies.length ; i++) {
            if (cookies[i].getName().equals("name")) {
                Cookie cookie = new Cookie("name",
                         URLEncoder.encode("JSP프로그래밍"));
                response.addCookie(cookie);
                //cookies[i].setValue(URLEncoder.encode("자바와 JSP"));
                //response.addCookie(cookies[i]);
            }
        }
    }
%>
<html>
<head><title>값 변경</title></head>
<body>
name 쿠키의 값을 변경합니다.
</body>
</html>

 


:::쿠키 삭제:::
<%@ page contentType = "text/html; charset=euc-kr" %>
<%@ page import! = "java.net.URLEncoder" %>
<%
    Cookie[] cookies = request.getCookies();
    if (cookies != null && cookies.length > 0) {
        for (int i = 0 ; i < cookies.length ; i++) {
            if (cookies[i].getName().equals("name")) {
                Cookie cookie = new Cookie("name", "");
                cookie.setMaxAge(0);
                response.addCookie(cookie);
            }
        }
    }
%>
<html>
<head><title>쿠키 삭제</title></head>
<body>
name 쿠키를 삭제합니다.
</body>
</html>

 


:::쿠키의 도메인:::
<%@ page contentType = "text/html; charset=euc-kr" %>
<%@ page import! = "java.net.URLEncoder" %>
<%
    Cookie cookie1 = new Cookie("id", "madvirus");
    cookie1.setDomain(".madvirus.net");
    response.addCookie(cookie1);
   
    Cookie cookie2 = new Cookie("only", "onlycookie");
    response.addCookie(cookie2);

    Cookie cookie3 = new Cookie("invalid", "invalidcookie");
    cookie3.setDomain("javateam.korea.ac.kr");
    response.addCookie(cookie3);
%>
<html>
<head><title>쿠키생성</title></head>
<body>

다음과 같이 쿠키를 생성했습니다.<br>
<%= cookie1.getName() %>=<%= cookie1.getValue() %>
[<%= cookie1.getDomain() %>]
<br>
<%= cookie2.getName() %>=<%= cookie2.getValue() %>
[<%= cookie2.getDomain() %>]
<br>
<%= cookie3.getName() %>=<%= cookie3.getValue() %>
[<%= cookie3.getDomain() %>]

</body>
</html>

 

:::쿠키의 경로:::
<%@ page contentType = "text/html; charset=euc-kr" %>
<%@ page import! = "java.net.URLEncoder" %>
<%
    Cookie cookie1 = new Cookie("path1",
                     URLEncoder.encode("경로:/chap09/path1"));
    cookie1.setPath("/chap09/path1");
    response.addCookie(cookie1);
   
    Cookie cookie2 = new Cookie("path2",
                     URLEncoder.encode("경로:"));
    response.addCookie(cookie2);
   
    Cookie cookie3 = new Cookie("path3",
                     URLEncoder.encode("경로:/"));
    cookie3.setPath("/");
    response.addCookie(cookie3);

    Cookie cookie4 = new Cookie("path4",
                     URLEncoder.encode("경로:/chap09/path2"));
    cookie4.setPath("/chap09/path2");
    response.addCookie(cookie4);
%>

<html>
<head><title>쿠키 경로 지정</title></head>
<body>

다음과 같이 쿠키를 생성했습니다.<br>
<%= cookie1.getName() %>=<%= cookie1.getValue() %>
[<%= cookie1.getPath() %>]
<br>
<%= cookie2.getName() %>=<%= cookie2.getValue() %>
[<%= cookie2.getPath() %>]
<br>
<%= cookie3.getName() %>=<%= cookie3.getValue() %>
[<%= cookie3.getPath() %>]
<br>
<%= cookie4.getName() %>=<%= cookie4.getValue() %>
[<%= cookie4.getPath() %>]

</body>
</html>

 

:::쿠키의 유효시간 설정:::
<%@ page contentType = "text/html; charset=euc-kr" %>
<%
    Cookie cookie = new Cookie("oneh", "1time");
    cookie.setMaxAge(60 * 60); // 60초(1분) * 60 = 1시간
    response.addCookie(cookie);
%>
<html>
<head><title>쿠키유효시간설정</title></head>
<body>

유효시간이 1시간인 oneh 쿠키 생성.

</body>
</html>

 

 


:::쿠키생성클래스:::(.java)
//package jsp.util;

import! javax.servlet.http.HttpServletRequest;
import! javax.servlet.http.Cookie!
import! java.util.Map;
import! java.net.URLEncoder;
import! java.net.URLDecoder;
import! java.io.IOException;

public class CookieBox {
   
    private Map cookieMap = new java.util.HashMap();
   
    public CookieBox(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (int i = 0 ; i < cookies.length ; i++) {
                cookieMap.put(cookies[i].getName(), cookies[i]);
            }
        }
    }
   
    public static Cookie createCookie(String name, String value)
    throws IOException {
        return new Cookie(name, URLEncoder.encode(value, "euc-kr"));
    }

    public static Cookie createCookie(
            String name, String value, String path, int maxAge)
    throws IOException {
        Cookie cookie = new Cookie(name,
                                URLEncoder.encode(value, "euc-kr"));
        cookie.setPath(path);
        cookie.setMaxAge(maxAge);
        return cookie;
    }
   
    public static Cookie createCookie(
            String name, String value, 
            String domain, String path, int maxAge)
    throws IOException {
        Cookie cookie = new Cookie(name,
                                URLEncoder.encode(value, "euc-kr"));
        cookie.setDomain(domain);
        cookie.setPath(path);
        cookie.setMaxAge(maxAge);
        return cookie;
    }
   
    public Cookie getCookie(String name) {
        return (Cookie)cookieMap.get(name);
    }
   
    public String getValue(String name) throws IOException {
        Cookie cookie = (Cookie)cookieMap.get(name);
        if (cookie == null) return null;
        return URLDecoder.decode(cookie.getValue(), "euc-kr");
    }
   
    public boolean exists(String name) {
        return cookieMap.get(name) != null;
    }
}

 

 

:::클래스를 이용한 쿠키생성:::
<%@ page contentType = "text/html; charset=euc-kr" %>
<%@ page import! = "jsp.util.Cookie!Box" %>
<%
    response.addCookie(CookieBox.createCookie("name", "최범균"));
    response.addCookie(
        CookieBox.createCookie("id", "madvirus", "/chap09", -1));
%>
<html>
<head><title>CookieBox사용예</title></head>
<body>

CookieBox를 사용하여 쿠키 생성

</body>
</html>

 


:::클래스를 이용한 쿠키읽기:::
<%@ page contentType = "text/html; charset=euc-kr" %>
<%@ page import! = "jsp.util.Cookie!Box" %>
<%
    CookieBox cookieBox = new CookieBox(request);
%>
<html>
<head><title>Cookie 사용</title></head>
<body>

name 쿠키 = <%= cookieBox.getValue("name") %> <br>
<%  if (cookieBox.exists("id")) { %>
id 쿠키 = <%= cookieBox.getValue("id") %> <br>
<%  }  %>
</body>
</html>

 


:::로그인폼:::
<%@ page contentType = "text/html; charset=euc-kr" %>
<html>
<head><title>로그인폼</title></head>
<body>

<form action="<%= request.getContextPath() %>/member/login.jsp"
      method="post">
아이디 <input type="text" name="id" size="10">
암호 <input type="password" name="password" size="10">
<input type="submit" value="로그인">
</form>

</body>
</html>

 

:::로그인:::
<%@ page contentType = "text/html; charset=euc-kr" %>
<%@ page import! = "jsp.util.Cookie!Box" %>
<%
    String id = request.getParameter("id");
    String password = request.getParameter("password");
   
    if (id.equals(password)) {
        // ID와 암호가 같으면 로그인에 성공한 것으로 판단.
        response.addCookie(
            CookieBox.createCookie("LOGIN", "SUCCESS", "/", -1)
        );
        response.addCookie(
            CookieBox.createCookie("ID", id, "/", -1)
        );
%>
<html>
<head><title>로그인성공</title></head>
<body>

로그인에 성공했습니다.

</body>
</html>
<%
    } else { // 로그인 실패시
%>
<script>
alert!("로그인에 실패하였습니다.");
history.go(-1);
</script>
<%
    }
%>

 


:::로그아웃:::
<%@ page contentType = "text/html; charset=euc-kr" %>
<%@ page import! = "jsp.util.Cookie!Box" %>
<%
    response.addCookie(
        CookieBox.createCookie("LOGIN", "", "/", 0)
    );
    response.addCookie(
        CookieBox.createCookie("ID", "", "/", 0)
    );
%>
<html>
<head><title>로그아웃</title></head>
<body>

로그아웃하였습니다.

</body>
</html>

 


:::세션정보:::
<%@ page contentType = "text/html; charset=euc-kr" %>
<%@ page session = "true" %>
<%@ page import! = "java.util.Date" %>
<%@ page import! = "java.text.SimpleDateFormat" %>
<%
    Date time = new Date();
    SimpleDateFormat formatter =
       new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
%>
<html>
<head><title>세션정보</title></head>
<body>
세션ID: <%= session.getId() %> <br>
<%
    time.setTime(session.getCreationTime());
%>
세션생성시간: <%= formatter.format(time) %> <br>
<%
    time.setTime(session.getLastAccessedTime());
%>
최근접근시간: <%= formatter.format(time) %>

</body>
</html>

 


:::세션생성:::
<%@ page contentType = "text/html; charset=euc-kr" %>
<%
    session.setAttribute("MEMBERID", "madvirus");
    session.setAttribute("NAME", "최범균");
    session.setMaxInactiveInterval(60*60); //시간설정
%>
<html>
<head><title>세션에 정보 저장</title></head>
<body>

세션에 정보를 저장하였습니다.

<% String name=(String)session.getAttribute("NAME"); %>
회원명: <%= name %>

</body>
</html>

 


:::세션종료:::
<%@ page contentType = "text/html; charset=euc-kr" %>
<%
    session.invalidate();
%>
<html>
<head><title>세션 종료</title></head>
<body>

세션을 종료하였습니다.

</body>
</html>

 


:::세션시간xml:::
<?xml version="1.0" encoding="euc-kr"?>

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">
  <display-name>9장 예제</display-name>
  <description>
     9장의 예제 소스 코드 및 실행 코드
  </description>
 
  <session-config>
    <session-timeout>1</session-timeout>
  </session-config>
</web-app>

 


:::세션로그인:::
<%@ page contentType = "text/html; charset=euc-kr" %>
<%@ page import! = "jsp.util.Cookie!Box" %>
<%
    String id = request.getParameter("id");
    String password = request.getParameter("password");
   
    if (id.equals(password)) {
        session.setAttribute("MEMBERID", id);
%>
<html>
<head><title>로그인성공</title></head>
<body>

로그인에 성공했습니다.

</body>
</html>
<%
    } else { // 로그인 실패시
%>
<script>
alert!("로그인에 실패하였습니다.");
history.go(-1);
</script>
<%
    }
%>

 


:::세션로그인폼:::
<%@ page contentType = "text/html; charset=euc-kr" %>
<html>
<head><title>로그인폼</title></head>
<body>

<form action="<%= request.getContextPath() %>/member/sessionLogin.jsp"
      method="post">
아이디 <input type="text" name="id" size="10">
암호 <input type="password" name="password" size="10">
<input type="submit" value="로그인">
</form>

</body>
</html>

 

:::세션로그인여부검사:::
<%@ page contentType = "text/html; charset=euc-kr" %>
<%
    String memberId = (String)session.getAttribute("MEMBERID");
    boolean login = memberId == null ? false : true;
%>
<html>
<head><title>로그인여부 검사</title></head>
<body>

<%
    if (login) {
%>
아이디 "<%= memberId %>"로 로그인 한 상태
<%
    } else {
%>
로그인하지 않은 상태
<%
    }
%>
</body>
</html>

 

:::세션로그아웃:::
<%@ page contentType = "text/html; charset=euc-kr" %>
<%
    session.invalidate();
%>
<html>
<head><title>로그아웃</title></head>
<body>

로그아웃하였습니다.

</body>
</html>

출처 : http://blog.daum.net/lifestyling/7969214