일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- #프로그래머스
- #프로그래머스 #코딩 #문자열잘라서정렬하기
- #프로그래머스 #코딩 #자바 #리스트자르기
- #프로그래머스 #코딩 #자바 #문자열묶기
- #프로그래머스 #코딩 #자바 #문자열여러번뒤집기
- #프로그래머스 #코딩 #l로만들기
- #JSP #Servlet #Ajax #에이젝스 #HTML #success #.HTML() #HTML로붙이기
- #JSP #Servlet #제이에스피 #서블릿 #필터 #filter #web.xml #필터예제 #filter예제
- #git #commit #message #깃커밋 #메시지 #gitmessage #누락 #reset #mixed #마지막커밋정정하기
- #프로그래머스 #코딩 #자바 #왼쪽오른쪽
- #프로그래머스 #코딩 #자바 #수열과구간쿼리1
- #프로그래머스 #코딩 #자바 #2의영역
- #프로그래머스 #코딩 #글자지우기 #자바
- #프로그래머스 #코딩 #자바 #빈배열에추가삭제하기
- #프로그래머스 #코딩 #문자열뒤집기 #자바
- #프로그래머스 #코딩 #자바 #수열과구간쿼리3
- #JSP #Servlet #제이에스피 #서블릿 #필터 #Filter @WebFilter #어노테이션필터
- #프로그래머스 #자바 #코딩 #배열만들기2
- #프로그래머스 #자바 #코딩 #특정문자열로끝나는가장긴부분문자열찾기
- 코딩 #자바 #조건에맞게수열변환하기2
- #프로그래머스 #자바 #코딩 #전국대회선발
- #프로그래머스 #코딩 #x사이의개수
- #프로그래머스 #자바 #코딩 #무작위로k개의수뽑기
- #프로그래머스 #코딩 #자바 #문자열이몇번등장하는지세기
- #프로그래머스 #코딩 #배열원소 삭제하기
- #프로그래머스 #코딩 #배열의길이에따라다른연산하기
- #프로그래머스 #코딩 #배열비교하기
- #프로그래머스 #코딩 #자바 #수열과구간쿼리2
- #프로그래머스 #코딩 #순서바꾸기
- #프로그래머스 #코딩 #배열만들기3
- Today
- Total
David의 블로그
[JSP/Servlet]정보를 저장할 수 있는 객체 쿠키.Cookie 본문
[Cookie. 쿠키란??]
자바에서 쿠키란, 웹 브라우저(클라이언트)에서 정보를 저장할 수 있는 객체를 말한다.
실제 프로젝트에서 적용 예제를 보자면, '하루동안 팝업 열지 않기'라든가 '아이디 저장하기' 같은
사례가 있다.
[사용하는 이유]
'아이디 저장하기'라든가 쇼핑몰 사이트에서 '내가 본 장바구니' 기능을 쿠키로 만들어 놓으면 편리하기 때문에 사용한다.
아래는 유틸 쿠키 클래스를 살펴보도록 하겠다.
[Cookie2.java]
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
package util;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.net.http.HttpRequest;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
public class Cookie2 {
private Map<String, Cookie> cookieMap = new HashMap<>();
// response에 쿠키를 추가 한 뒤에
// request로 쿠키[]으로 정의 할 수 있다.
// Map<String, Cookie> 객체를 이용하여
// "쿠키네임" : "쿠키"로 초기화를 해준다.
public Cookie2(HttpServletRequest req) {
Cookie[] cookies = req.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
cookieMap.put(cookies[i].getName(), cookies[i]);
}
}
}
// 해당 네임의 쿠키 가져오기.
public Cookie getCookie(String name) {
return cookieMap.get(name);
}
// 해당 네임의 쿠키값 가져오기.
public String getValue(String name) throws IOException{
Cookie cookie = cookieMap.get(name);
if (cookie == null) {
return null;
} else {
return URLDecoder.decode(cookie.getValue(), "euc-kr");
}
}
// 해당 쿠키가 존재유무 메소드
// 값이 존재한다면 true / 존재하지 않는다면 false
public boolean exits(String name) {
return cookieMap.get(name) != null;
}
// 첫 번째. 쿠키 생성
// 네임과 벨류값을(키 : 값) 받아 쿠키를 생성한다.
public static Cookie createCookie(String name, String value) throws IOException{
return new Cookie(name, URLEncoder.encode(value, "utf-8"));
}
// 두 번째. 쿠키 생성
// 네임과 벨류값(키 : 값) , 유효기간 값을 받아 쿠키를 생성한다.
public static Cookie createCookie(String name, String value, int maxAge) throws IOException{
Cookie cookie = new Cookie(name, URLEncoder.encode(value, "utf-8"));
cookie.setMaxAge(0);
return cookie;
}
}
|
cs |
52, 58Line : createCookie 메소드를 생성해 줄 때, static으로 선언하여 만들어줬다. static이 없다면 에러가 난다.
이 쿠키 유틸 클래스로
쿠키 생성과 읽어오기 메소드들을 활용하여 쿠키의 존재 유무로 보여주는 화면을 달리하는 예제를 만들어 보았다.
[CookieServlet.java]
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
34
35
36
37
38
39
40
41
|
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import util.Cookie2;
@WebServlet(urlPatterns = {"/index.do", "/cookie.do"})
public class CookieServlet extends HttpServlet {
Cookie2 cookie2 = null;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
// 쿠키를 생성합니다.
System.out.println("cookie 서블릿에 오신 것을 환영합니다.");
resp.setContentType("text/html; charset=utf-8");
PrintWriter out = resp.getWriter();
out.println("<div>");
out.println("<h2 align=\"center\">쿠키 연습용 팝업</h2>");
out.println("<div>");
out.println("<form action=\"./popupCheck.do\" method=\"post\">");
out.println("<input type =\"checkbox\" name = \"popupCheck\" value=\"1\" />\r\n"
+ " <input type=\"button\" value=\"닫기\" />");
out.println("<input type=\"submit\" value=\"확인\" />");
out.println("</form>");
out.println("</div>");
out.println("</div>");
}
}
|
cs |
PrintWriter 클래스를 이용해 간단하게 폼 HTML을 만들어 주었다.
화면이라곤 체크박스 하나와 '취소'(아무동작없는) 버튼과 '확인'(서버 전송) 버튼을 만들었다.
기능은 checkbox를 클릭하고 확인을 누르면,
다음 서블릿에서 유효성 체크를 하고 쿠키를 생성하는 간단한 기능을 넣어놓았다.
[PopupServlet.java]
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import util.Cookie2;
@WebServlet(urlPatterns = "/popupCheck.do")
public class PopupServlet extends HttpServlet{
Cookie2 cookie2 = null;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
//super.doPost(req, resp);
process(req, resp);
}
private void process(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
res.setContentType("text/html; charset=utf-8");
req.getParameter("popupCheck");
// checkbox 체크 값.
String checkVal = req.getParameter("popupCheck");
PrintWriter out = res.getWriter();
// 체크박스 체크를 했으면,
// 쿠키 만들어주기.
if ("1".equals(checkVal)) {
res.addCookie(
cookie2.createCookie("popupBool", "close")
);
// res.addCookie(
// cookie2.createCookie("popupBool", "close", 0)
// );
}
// 쿠키 요청
cookie2 = new Cookie2(req);
// System.out.println(cookie2.getCookie("test1"));
// System.out.println(cookie2.getValue("test1"));
// 요청에 쿠키가 존재한다면
if (cookie2.exits("popupBool"))
{
out.println("<div>");
out.println("<h2 align=\"center\">쿠키 값 생성되고 난 후 화면</h2>");
out.println("<div>");
out.println("<h3>쿠키가 생성 되어 팝업이 없어졌습니다.!!!");
out.println("</h3>");
out.println("</div>");
out.println("</div>");
}
// 쿠키가 존재하지 않는다면
else
{
out.println("<div>");
out.println("<h2 align=\"center\">쿠키 만들어지기 전 화면</h2>");
out.println("<div>");
out.println("<form action="+req.getContextPath()+"/popupCheck.do method=post>");
out.println("<input type =\"checkbox\" name = \"popupCheck\" value=\"1\" />\r\n"
+ " <input type=\"button\" value=\"닫기\" />");
out.println("<input type=\"submit\" value=\"확인\" />");
out.println("</form>");
out.println("</div>");
out.println("</div>");
}
}
}
|
cs |
37Line : 체크박스 값을 체크했는지 유효성 체크를 한다.
39Line : 쿠키 유틸클래스 메소드인 쿠키를 생성하고 HttpResponseServlet 객체에 추가를 해준다.
42Line : 쿠키 생성 메소드로 쿠키네임, 쿠키 값, 쿠키 유효시간을 넣었다.
48Line : 쿠키 생성자 메소드이다.
[결과]
[느낀 점]
쿠키는 객체를 만들고 바로 사용할 수 없는 것 같다.
쿠키는 서버에서 만들어진다.
웹 브라우저(클라이언트)에서 최초 요청을 하면 서버에서 쿠키를 생성하여 응답객체(response) 헤더에 쿠키를 저장하여
웹 브라우저에 전송한다.
이후 웹 브라우저에서 요청을 있을 때마다 쿠키와 함께 서버로 전송하기 때문인 것 같다
'프로그래밍 > Jsp_Servlet' 카테고리의 다른 글
[JSP/Servlet]상태를 유지할 수 있는 Session, 세션(두번째) (0) | 2024.01.20 |
---|---|
[JSP/Servlet]상태를 유지할 수 있는 Session, 세션(첫번째) (0) | 2024.01.20 |
[JSP/Servlet]Listener 리스너 (2) | 2023.12.19 |
[JSP/Servlet] Custom Error페이지 만들기3 (1) | 2023.12.02 |
[JSP/Servlet] Custom Error페이지 만들기2 (0) | 2023.12.02 |