Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- iframe
- Import
- 빈즈
- opener
- target
- 동기 부여
- ;
- 로그인화면
- 페이지이동
- 동기부여
- \
- 자바빈즈
- session.getAttribute
- 페이지 이동
- BEANS
- 영감
- 향상된 for문
- "
- 파일 호출
- 팝업창
- session.setAttribute
- 미래직장
- 데이터사이언스
- 파일호출
- scanner
- Alert
- javaBeans
- session.removeAttribute
- static
- 버리자
Archives
- Today
- Total
갈림길 이정표
[Servlet] Cookie 와 Session의 차이 본문
[web_pro3 > main.html(일부)]
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
.
.
.
<hr>
<a href="getdata.html">get으로 자료 전달 </a><br>
<a href="postdata.html">post으로 자료 전달 </a>
<br><br>
<a href="CookieLogin">쿠키 연습 </a><br>
쿠키: 서버가 클라이언트에 정보를 기억하게끔 과자 부스러기 처럼 흘리는 것 (아무런 조건 없으면 무조건 get방식)<br>
<a href="SessionTest">세션 연습 </a><br>
세션: 클라이언트의 정보를 서버에 기억
</body>
</html>
[CookieLogin.java]
package pack;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/CookieLogin")
public class CookieLogin extends HttpServlet {
//클라이언트가 강제로 지우거나 유효기간 만료 되지 않는 한 비휘발성 기록
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.print("<html><body>");
//쿠키가 없는 경우 로그인 화면 출력
String id = null; //쿠키가 없는 지 부터 확인 (유효기간이나 밀려났는 지 확인)
String pwd = null;
//why 유효성 검사?
try {
Cookie[] cookies = request.getCookies(); //클라이언트 컴퓨터 내 모든 쿠키 읽음
for (int i = 0; i < cookies.length; i++) {
String name = cookies[i].getName();
System.out.println("name: " + name); //자꾸 출력하여 확.인.하.는.습.관.을 들이자
if(name.equals("myId")) {
id = URLDecoder.decode(cookies[i].getName(), "utf-8"); //Encoder된 정보 Decoder함
}
if(name.equals("myPwd")) {
pwd = URLDecoder.decode(cookies[i].getName(), "utf-8");
}
}
} catch (Exception e) {
}
if(id != null && pwd != null) {
out.print(id + " : 쿠키를 통해 로그인한 상태입니다.");
out.print("</body></html>");
out.close();
return; //(쿠키가 존재하는 한) 밑의 내용 수행 안함 -> Cookie: (서버가 아닌) 클라이언트에 저장되는 기록들
}
out.print("**로그인**<br>");
out.print("<form method='post'>"); //action 이 없으면 자기가 자기를 부르는 꼴 //doGet메소드를 통해 doPost 메소드를 부를 것임
out.print("id: <input type='text' name='id' value='aa'><br>");
out.print("pwd: <input type='text' name='pwd'><br>");
out.print("<input type='submit' value='전송'>");
out.print("</form>");
out.print("</body></html>");
out.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
String id = request.getParameter("id");
String pwd = request.getParameter("pwd");
out.print("<html><body>");
if(id.equals("aa") && pwd.equals("123")) {
out.println("로그인 성공 - 쿠키 작성됨");
//로그인 성공시에만 쿠키 생성할 경우
try {
id = URLEncoder.encode(id, "utf-8"); //받아온 정보 암호화 됨
pwd = URLEncoder.encode(pwd, "utf-8");
Cookie idCookie = new Cookie("myId", id); //javax.servlet Class Cookie (Key, value)로 받아옴
idCookie.setMaxAge(60 * 60 * 24 * 365); //1년 유효기간 설정 법 (초, 분, 시간, 년 순)
Cookie pwdCookie = new Cookie("myPwd", pwd);
pwdCookie.setMaxAge(60 * 60 * 24 * 365);
//※단, FIFO방식이므로 유효기간 전에도 밀려날 수 있음
response.addCookie(idCookie); //클라이언트에 저장
response.addCookie(pwdCookie);
} catch (Exception e) {
}
}else {
out.println("로그인 실패");
}
out.print("</body></html>");
}
}
[SessionTest.java]
package pack;
import java.io.IOException;
import java.io.PrintWriter;
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 javax.servlet.http.HttpSession;
@WebServlet("/SessionTest")
public class SessionTest extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//각 클라이언트의 정보를 웹 서버에 메모리 확보 후 기억 (휘발성) - why? 메모리가 한정적이므로
HttpSession session = request.getSession(true); //세션이 있으면 읽고 없으면 생성 O
//HttpSession session = request.getSession(false); //세션이 있으면 읽고 없으면 생성 X
session.setMaxInactiveInterval(10); //유효시간 설정 (default = 30 min) 절대시간이 아니라 비활성화되는 시점 부터 다시 재시작됨
//세션 값 고정 시키고 싶으면 web.xml에 저장하기 (우선순위 1순위)
if(session != null)
session.setAttribute("name", "홍길동");
//서버에 접속한 클라이언트 정보를 기억 (읽을 때는 get) | key,value 싸은 여러개 담을 수 있음
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.print("<html><body>");
out.print("session ID: " + session.getId()); //session id는 고유함 (hexa[16진수] 값)
out.print("<br>사용자명 " + session.getAttribute("name"));
out.print("</body></html>");
}
}
'Programming Language > Servlet & JSP' 카테고리의 다른 글
[Servlet] Example 1. 간단한 쇼핑몰 만들기 (feat. Session, DTO) (0) | 2020.08.25 |
---|---|
[Servlet] 작동이 안될 때 (0) | 2020.08.25 |
[Servlet] 입력자료 방식 Get/Post 차이 (0) | 2020.08.24 |
[Servlet] 게시물 작성(DB에 저장하고 불러오기) (0) | 2020.08.24 |
[Servlet] 쇼핑몰 구현하기 (쿠키, 세션) (0) | 2020.08.24 |
Comments