[JSP/Servlet] Cookie 기본 예제
- BACKEND/Servlet&JSP
- 2017. 5. 11. 18:24
●목록
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<display-name>cookieset</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>GetCookieServlet</servlet-name>
<servlet-class>servlet.cookie.GetCookieServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GetCookieServlet</servlet-name>
<url-pattern>/cookie/get</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>SetCookie1Servlet</servlet-name>
<servlet-class>servlet.cookie.SetCookie1Servlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SetCookie1Servlet</servlet-name>
<url-pattern>/cookie/set1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>SetCookie2Servlet</servlet-name>
<servlet-class>servlet.cookie.SetCookie2Servlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SetCookie2Servlet</servlet-name>
<url-pattern>/cookie/set2</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>SetCookie3Servlet</servlet-name>
<servlet-class>servlet.cookie.SetCookie3Servlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SetCookie3Servlet</servlet-name>
<url-pattern>/cookie/set3</url-pattern>
</servlet-mapping>
</web-app>
request.jsp
<%@ page contentType="text/html;charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="/cookieset/cookie/set1">SetCookie 1 호출</a><br>
<a href="/cookieset/cookie/get">GetCookie 호출</a><br>
<a href="/cookieset/cookie/set3">SetCookie 3 호출 - currentTime 쿠키 삭제</a>
<form action="/cookieset/cookie/set2" method="post">
ID : <input type="text" name="id"><br>
키워드 : <input type="text" name="keyword"><br>
<input type="submit" value="전송">
</form>
</body>
</html>
response.jsp
<%@ page contentType="text/html;charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>쿠키 값들</h2>
<!-- 서블릿에서 req로 변수를 설정했어도 JSP에서는 무조건 request로 불러와야한다. -->
<%= request.getAttribute("message") %>
<p>
<a href="/cookieset/cookie/request.jsp">request.jsp</a>
</p>
</body>
</html>
SetCookie1Servlet.java
package servlet.cookie;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
// 쿠키값 설정
public class SetCookie1Servlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//현재 실행 시점의 시간을 Cookie로 설정
//현재 시간 Date 객체 생성 - java.util.Date import
Date date = new Date();
String currentTime = new SimpleDateFormat("HH:mm:ss").format(date); // name/value가 String으로만 받아야하므로 String타입으로 변환
//쿠키객체 생성
Cookie cookie = new Cookie("currentTime",currentTime);
//웹브라우저에 전송
resp.addCookie(cookie);
//request.jsp로 이동 (요청 디스패치)
RequestDispatcher rdp = req.getRequestDispatcher("/cookie/request.jsp");
rdp.forward(req, resp);
}
}
SetCookie2Servlet.java
package servlet.cookie;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//쿠키값 변경
public class SetCookie2Servlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1. 요청파라미터 조회
req.setCharacterEncoding("utf-8");
String id = req.getParameter("id");
String keyword = req.getParameter("keyword");
//2. id=값, keyword=값 => 쿠키로 전송 (값 : 한글X) -> 영문 or 숫자로만
//쿠키 이름이 id인 것이 있으면(웹브라우저가 전송했으면) id쿠키는 변경 하지 않는다
//쿠기 조회
Cookie[] cookies = req.getCookies();
boolean flag = false;
if(cookies!=null){
for(Cookie c : cookies){
if(c.getName().equals("id")){
flag = true;
break;
}
}
}
if(!flag){
Cookie cookie1 = new Cookie("id",id);
resp.addCookie(cookie1);
}
Cookie cookie2 = new Cookie("keyword",keyword);
resp.addCookie(cookie2);
//3. 응답 : request.jsp 로 이동
req.getRequestDispatcher("/cookie/request.jsp").forward(req, resp);
}
}
SetCookie3Servlet.java
package servlet.cookie;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//쿠키값 삭제
public class SetCookie3Servlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//전송된 쿠키중 이름이 currentTime인 쿠키를(Web Browser에서) 삭제
Cookie c = new Cookie("currentTime","1"); //Value값은 아무거나 줘도 된다.
c.setMaxAge(0);
resp.addCookie(c);
//응답 : request.jsp로 이동
req.getRequestDispatcher("/cookie/request.jsp").forward(req, resp);
}
}
●결과
'BACKEND > Servlet&JSP' 카테고리의 다른 글
[JSP/Servlet] Expression Language 정의 및 간단한 확인 예제 (0) | 2017.05.16 |
---|---|
[JSP/Servlet] JSP 동적 부분 (0) | 2017.05.15 |
[JSP/Servlet] Cookie 예제 -숫자 누적처리 (0) | 2017.05.11 |
[JSP/Servlet] Listener 및 ServletContext/ServletConfig 예제 (0) | 2017.05.10 |
[JSP/Servlet] Form 예제 (0) | 2017.05.10 |