2019.01.30 Cookie 만들기(1)

2019. 1. 30. 16:34JSP


<cookeis-personalize-form.html>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>personalize the site</title>
</head>
<body>
    <form action="cookies-personlize-response.jsp">
        Select your Favorite Programming Language
        <select name ="favoriteLanguage">
            <option>Java</option>
            <option>C#</option>
            <option>PHP</option>
            <option>Ruby</option>
        </select>
        
        <br/><br/>
        
        <input type="submit" value="Submit"/>
    </form>
 
</body>
</html>
cs




<cookeis-personlize-response.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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Confirmation</title>
</head>
    <% 
        // read form data
        String favLang = request.getParameter("favoriteLanguage");
        // create the cookie
        Cookie theCookie = new Cookie("myApp.favoriteLanguage",favLang);
        // set the life span .. total number of seconds (yuk!)
        theCookie.setMaxAge(60*60*24*365); // <--for one year,쿠키의 유효기간
        // send cookie to browser
        response.addCookie(theCookie);
    %>
<body>
    Thanks! we set your favorite language to : ${param.favoriteLanguage}
    <br/><br/>
    <a href="cookies-homepage.jsp">Return to homepage.</a>
</body>
</html>
cs


<cookies-homepage.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
27
28
29
30
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Training Portal</title>
</head>
<body>
    <h3>Training Portal</h3>
    <!-- read the favorite programming language cookie -->
    
    <%
        // the default.. if there are no cookies
        String favLang ="Java";
        // get the cookies from the browser requset
        Cookie[] theCookies = request.getCookies();
        // find our favorite language cookie
        if(theCookies != null){
            for(Cookie tempCookie : theCookies){
                if("myApp.favoriteLanguage".equals(tempCookie.getName())){
                    favLang =tempCookie.getValue();
                    out.print(favLang); // 생성된 쿠키의 값을 확인
                    break;
                }
            }
        }
    %>
</body>
</html>
cs



실행화면▼▼





>>생성된 쿠키확인



'JSP' 카테고리의 다른 글

2019.01.31 Session의 이해  (0) 2019.01.31
2019.01.31 get형식 & post형식  (0) 2019.01.31
2019.01.30 JSTL 라이브러리  (0) 2019.01.30
2019.01.29 error : 에러페이지  (0) 2019.01.29
2019.01.29 JSP 기본예제#1  (0) 2019.01.29