Jam's story
[JSP] 클라이언트와 대화 - 쿠키 본문


ex02.jsp
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<link rel="shortcut icon" type="image/x-icon" href="../images/SiSt.ico">
<title>2022. 6. 21.-오후 4:24:22</title>
</head>
<body>
<h3></h3>
<a href="ex02_02.jsp">jsp쿠키 생성</a>
<a href="ex02_03.jsp">jsp쿠키 확인</a>
<pre>
클라이언트와의 대화 =쿠키
</pre>
</body>
</html>
ex02_setCookie.jsp
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<link rel="shortcut icon" type="image/x-icon" href="../images/SiSt.ico">
<title>2022. 6. 21.-오후 4:40:42</title>
</head>
<body>
<h3></h3>
<form action="ex02_02_ok.jsp" method="get">
생성할 쿠키 이름 : <input type="text" name="cookieName" value=""><br>
생성할 쿠키 값: <input type="text" name="cookieValue" value="홍길동"><br>
<input type="submit">
</form>
</body>
</html>
ex02_setCookie_ok.jsp
<%@page import="java.net.URLEncoder"%>
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!-- 쿠키만 생성할 것이니 화면에 보일 html 코딩 필요 없겠다 -->
<%
String cname = request.getParameter("cname");
String cvalue = request.getParameter("cvalue");
//***[주의]*** 값 저장시
Cookie cookie = new Cookie(cname, URLEncoder.encode(cvalue,"UTF-8") );
//cookie.setDomain(domain); 안주면 로컬호스트 잡힘
cookie.setPath("/"); //경로 WebContent밑의 모든 요청을 쿠키값 가지고 전송하겠다는 의미
cookie.setMaxAge(-1); //음수 값을 만료시점으로 입력할 경우 웹브라우저를 닫을 때 쿠키 자동 삭제
//0(즉시 지워라) -1(브라우저 종료시 지워라)
response.addCookie(cookie); //쿠키에 저장하라는 명령
response.sendRedirect("ex02.jsp");
//서버에서 쿠키를 생성하는 게 아니라 명령을 내리는 것 (알려주는 역할 뿐) 실제 저장은 안일어남
//명령어가 들어있다고 생각
%>
ex02_03.jsp
<form action="ex02_02_ok.jsp" method="get">
생성할 쿠키 이름 : <input type="text" name="cookieName" value=""><br>
생성할 쿠키 값: <input type="text" name="cookieValue" value="홍길동"><br>
<input type="submit">
</form>
ex02_02_ok.jsp
쿠키생성하는 jsp
쿠키 유효기간을 설정한다. 초단위 : 60*60*24= 1일
c.setMaxAge(60*60*24) ;
응답헤더에 쿠키를 추가한다.
response.addCookie(c) ;
회원번호를 쿠키에 지정한다
Cookie c = new Cookie("memberNo", memberNo) ;
쿠키값이 한글이라면 utf-8 설정해주기
String cookieName=request.getParameter("cookieName"); String cookieValue=request.getParameter("cookieValue");
Cookie cookie = new Cookie(cookieName, URLEncoder.encode(cookieValue,"UTF-8") );
<%@page import="java.net.URLEncoder" %>
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
//쿠키생성
//Cookie c=new Cookie(쿠키이름,쿠키값 );
String cookieName=request.getParameter("cookieName");
String cookieValue=request.getParameter("cookieValue");
Cookie cookie=new Cookie(cookieName,URLEncoder.encode(cookieValue, "UTF-8"));
//js반드시 주의
//jsp 반드시 주의 --쿠키값이 한글일경우 utf-8 인코딩필요
//2. c.setDomain(domain) localhost
//c.setPath(url)
//브라우저종료시에 쿠키를 지운다.
//0이면 즉시 지워라
cookie.setMaxAge(-1);
//경로 webContent밑의 모든 요청을 쿠키값가지고 전송하겠다는 의미
cookie.setPath("/");
//쿠키에 저장해라
response.addCookie(cookie);
//리다이렉트
String location="ex02.jsp";
response.sendRedirect(location);
%>
ex02_03.jsp 쿠키확인
<form>
<%
//요청할때
//전달된 모든 쿠키들을 배열형태로 얻어옴
String cname, cvalue;
Cookie[] cookies=request.getCookies();
for(Cookie c:cookies){
cname=c.getName();
cvalue=URLDecoder.decode(c.getValue(),"UTF-8");
%>
<input type="checkbox" name="chbCookie" value="<%=cname %>" ><%=cname %>-<%=cvalue %><br>
<%
}
%>
</form>
ex02_04.jsp
쿠키삭제
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
//js쿠키삭제? 쿠키 새로 생성+만료시점 과거
//jsp 쿠키 삭제? c.setMaxAge(-1)브라우저 종료=> 자동삭제
// (0) 쿠키 바로 삭제
String[] del_cnames=request.getParameterValues("ckbCookie");
for(int i=0; i<del_cnames.length; i++){
Cookie c=new Cookie(del_cnames[i],"");
c.setMaxAge(0); // 바로삭제
response.addCookie(c); //쿠키객체를 웹 브라우저로 보낸다 .
}
%>
<script>
alert("체크한 쿠키 모두 삭제 완료 ");
location.href="ex02_03.jsp";
</script>
ex02_05.jsp
<%@page import="java.net.URLDecoder"%>
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>2022. 6. 22. - 오전 9:21:03</title>
<link rel="shortcut icon" type="image/x-icon" href="../images/SiSt.ico">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<h3>ex02_05.jsp</h3>
<%!
// js getCookie(cname) > value 반환
// 쿠키이름 > 쿠키값 반환
public String getCookie(String cname, HttpServletRequest request) throws Exception{
// request.getCookies()
String cvalue = null;
Cookie[] cookies = request.getCookies();
for(Cookie c:cookies){
if(c.getName().equals(cname)){
cvalue = URLDecoder.decode(c.getValue(),"UTF-8");
break; // 반복문 빠져나오기
}
}// foreach
return cvalue;
}
%>
<form action="ex02_05_ok.jsp">
<!-- ex02_05.jsp?chkCookie=name&ckbCookie=age -->
<%
String[] edit_cnames = request.getParameterValues("ckbCookie");
for(int i = 0; i < edit_cnames.length; i++){
String cname = edit_cnames[i];
%>
<!-- 표현식에서 선언문에 선언된 메서드 getCookie()를 호출할 수 있다. -->
<li><%= cname %>: <input type="text" name="<%= cname %>" value="<%= getCookie(cname,request) %>" /></li>
<%
}
%>
<input type="submit" value="쿠키수정" />
</form>
</body>
</html>
ex02_05_ok.jsp
<%@page import="java.net.URLEncoder"%>
<%@page import="java.util.Enumeration"%>
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!-- 실제 수정할 쿠키이름, 쿠키값 파라미터 전송 -->
<!-- <h3>ex02_05_ok.jsp</h3> -->
<%
// ?name=aaa&age=12
Enumeration<String> en = request.getParameterNames();
while( en.hasMoreElements() ){
String cname = en.nextElement();
String cvalue = request.getParameter(cname);
// 쿠키 생성 + 응답 포함
Cookie c = new Cookie( cname, URLEncoder.encode(cvalue, "UTF-8") );
c.setMaxAge( -1 ) ; // 브라우저 종료할때 쿠키 자동 삭제
response.addCookie( c );
} // while
String location = "ex02_03.jsp";
response.sendRedirect(location);
%>
-------------------------------------------------------------------
수정이랑 삭제안됨
'JSP' 카테고리의 다른 글
| [JSP] 커넥션풀 (0) | 2022.06.22 |
|---|---|
| [JSP] 로그인 화면 (0) | 2022.06.22 |
| [JSP] 게시판 - 목록, 글쓰기 기능 , 페이징 처리 (0) | 2022.06.20 |
| [JSP]자바빈즈 (0) | 2022.06.20 |
| [JSP] 페이지 모듈화와 요청 흐름 ->공통적인 부분 처리 (0) | 2022.06.20 |