본문 바로가기
Develop/Java Server Page

09. 클라이언트와의 대화 1 : 쿠키

by jaekk 2018. 7. 6.

 1. 쿠키 생성하기

 
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 language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import ="java.net.URLEncoder" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style>
</style>
</head>
<body>
 
<!-- 
    # 쿠키 만들기
    1. 쿠키 객체 생성
    2. 쿠키 전송
 -->
 
<%
    Cookie cookie = new Cookie("name",URLEncoder.encode("장민정","utf-8"));
    response.addCookie(cookie);
%>
</body>
</html>

cs

 

 2. 쿠기 값 읽어오기

 
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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.net.URLDecoder"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style>
</style>
</head>
<body>
    <!-- 
    #쿠키값 읽어오기
     1. 요청으로부터 쿠키를 받는다.
     2. 쿠키가 있으면
     3. 쿠키를 출력한다.
 -->
    <%
        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(), "utf-8")%><br>
    <%
            }
        } else {
    %>
        쿠키가 존재하지 않음
    <% } %>
</body>
</html>
cs

1. 쿠키값 변경하기 

 
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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import = "java.net.URLEncoder" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style>
</style>
</head>
<body>
<!-- 
    #쿠키 값 변경하기
    1. 쿠키를 가져온다. 
    2. 쿠키가 있으면
    3. 쿠키중에서 원하는 이름을 찾는다.
    4. 쿠키를 변경해서 저장한다.
-->
<%
    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프로그래밍","utf8"));
                response.addCookie(cookie);
            }
        }
    }
%>
</body>
</html>
cs


 


 


'Develop > Java Server Page' 카테고리의 다른 글

12. 표준 태그 라이브러리(JSTL)  (0) 2018.07.09
11. 표현 언어 Expression Language  (0) 2018.07.09
jsp 실습  (0) 2018.06.26
JSP 정리  (0) 2018.06.24
웹프로그래밍  (0) 2018.06.21

댓글