티스토리 뷰

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="setCookie.jsp">
		 성 : <input type="text" name="firstName"><br>
		 이름 : <input type="text" name="lastName"><br>
		 <br>
		 <input type="submit" value="전송"> 
	</form>
</body>
</html>

 

* 쿠키(Cookies)
- 웹 브라우저가 저장하는 데이터
- 필요한 정보를 클라이언트(웹 브라우저)에서 저장
 - 다양한 정보 추적을 목적으로 데이터가 유지됨 
 - 주로 브라우저에서 사용자가 선택한 내용들을 저장

setCookie.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSP Cookie</title>
</head>
<body>
	<%
	
		request.setCharacterEncoding("UTF-8");
		String firstName = request.getParameter("firstName");
		String lastName = request.getParameter("lastName");
	
		// 파라미터 값으로 쿠키 생성
		Cookie firstNameCookie = new Cookie("firstName",firstName);
		Cookie lastNameCookie = new Cookie("lastName",lastName);
		
		// 만료 시간 설정(초단위) : 24시간
		firstNameCookie.setMaxAge(60*60*24);
		lastNameCookie.setMaxAge(60*60*24);
		
		// response.header 에 쿠키를 추가 
		response.addCookie(firstNameCookie);
		response.addCookie(lastNameCookie);
		// Context Root에서 생성된 쿠키는 
		// 이 프로젝트에서만 사용됨
		
	%>
</body>
</html>

 

 

쿠키 가져오기 

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>쿠키 가져오기(GET)</title>
</head>
<body>
	<%
		Cookie[] cookies = request.getCookies();
	
		if(cookies != null){
			out.println("<h2>모든 쿠키의 이름과 값 찾기</h2>");
			for(Cookie cookie : cookies){
				out.print("name : " + cookie.getName() + "<br>");
				out.print("value : " + cookie.getValue() + "<br>");
				out.print(cookie.getComment() + "<br>");
			}
		}else{
			out.println("<h2>쿠키를 찾지 못했습니다.</h2>");
		}
	%>
</body>
</html>

 

 

 

저장된 id, pw 쿠키를 꺼내서 로그인 하기

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>로그인</title>
</head>
<body>
	<%
		//저장된 id, pw 쿠키를 꺼내서
		Cookie[] cookies = request.getCookies();
	
		String id = "";
		String pw = "";
		//input 태그(id,pw)에 값 보여주기
		if(cookies != null){
			for(Cookie cookie : cookies){
				
				if(cookie.getName().equals("id")){
					id =  cookie.getValue();
				}else if(cookie.getName().equals("pw")){
					pw = cookie.getValue();
				}
			
			}
		}else{
			out.println("<h2>쿠키를 찾지 못했습니다.</h2>");
		}
			%>
				

	<form action="practiceResult.jsp" method="post">
		아이디<br>
		<input type="text" name="id" value="<%=id %>"><br>
		비밀번호<br>
		<input type="password" name="pw" value="<%=pw %>"><br>
		<input type="checkbox" name="saveAgreed" value="agreed">
		아이디 저장<br><br>
		<input type="submit" value="로그인">
	</form>
</body>
</html>

 

form  POST 방식을 이용해서 쿠키에 저장된 id,pw를 practiceResult.jsp 로 보냄

 

 

practiceResult.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>로그인 결과 페이지</title>
</head>
<body>
	<%
		String userId = request.getParameter("id");
		String password = request.getParameter("pw");
		String saveAgreed = request.getParameter("saveAgreed"); //input -> request.getParameter()로 받는다 
		
		
		// practiceLogin.jsp에서 saveAgreed가 체크가 되어 있으면 
		if (saveAgreed != null){ 
		// id,pw에 대한 쿠키를 생성한다.
			Cookie idCookie = new Cookie("id",userId);
			Cookie pwCookie = new Cookie("pw",password);
		// 쿠키 만료 시간은 10분으로 설정.
			 idCookie.setMaxAge(60*10);
			 pwCookie.setMaxAge(60*10);
			 
			 response.addCookie(idCookie); // 다시 보내기
			 response.addCookie(pwCookie);
			 
		}else{
			out.println("<h2>쿠키를 찾지 못했습니다.</h2>");
		}	
	%>

	<h2>로그인 결과 화면</h2>
	<p><%=request.getParameter("id") %>님, 환영합니다.</p>
</body>
</html>

 

 

 


 

 

Cookie 과제 

 

practiceLogin.jsp

 

아이디 저장 체크박스를 체크하면 

아이디와 비밀번호가 저장되도록 하기

 

practiceResult.jsp

 

쿠키 코드 작성

 

practiceLogin.jsp

 

저장된 id,pw 쿠키를 꺼내서 

input 태그 (id,pw)에 값을 보내주기! 

 

 


 

내가 작성,,,

 

input 태크에 어케 값을 보여주지? 로 고민 했었다.

 

 


 

 

답안? 코드 

 

 

실행 화면

 

 

아이디 저장 체크박스를 체크하고 로그인을 누르면

 

 

로그인 결과 화면이 뜨고

 

 

로그인 페이지를 새로고침 하면 

아이디,비밀번호가 value 칸에 뜨게 만들어놨음

 


 

 

* HTTP 특성
- stateless protocol : 통신이 끝나면 상태를 유지하지 않는 특성
- 쿠키와 세션은 HTTP 특성이 아닌 연결 상태를 유지하기 위해 사용

* 세션(session)


- 쿠키를 기반으로 사용 
서버 측에서 데이터를 관리
- 세션 ID를 부여하여 브라우저를 종료할 때까지 데이터를 유지 
- 세션 객체 : 사용자를 식별할 수 있는 방법을 제공 
ㄴ 사용자에 대한 정보 저장
주의사항 : 세션은 현재 프로젝트에 실행되는 모든 웹 페이지에 적용됨! (따라서 다른 페이지에서 꺼내 쓸 수 있음)
  따라서, 하나의 클라이언트에 세션을 많이 사용하면 충돌이 발생할 수 있음!!
- session 객체는 session의 메소드를 사용하면 생성됨.
 (예.  session.setAttribute() )

HttpSession session = request.getSession();   //sevlet 세션 생성 

 

 

Session -> servlet(서버)에서 만드는게 좋음. 

jsp는 충돌할 수 있어서



Session 
HTTP : 상태 정보를 저장하지 않는 프로토콜

 

 


* Cookie와 Session 특성과 차이점(면접 단골 소재!!)


예 ) 카페 적립 쿠폰을 예로 들면 
Cookie : 적립 쿠폰을 손님(client)이 가지고 있음 
문제점 : 내(클라이언트)가 가지고 다님 -> 보안
장점 : 서버 저장 공간이 절약됨. (클라이언트에 저장됨)


Session : 적립 쿠폰을 가게(server)가 가지고 있음
문제점 : 사용자가 많을 수록 서버 부담 증가 
장점 :쿠키에 비해 보안이 강화 

 

 


 

 

세션 실습 

 

 

 

session 생성 

 

session.setAttribute()

 

주의할점 : 세션은 현재 프로젝트에 실행되는 모든 웹 페이지에 적용됨! 

다른 jsp 파일에서 "userId" 를 쓰는 경우 충돌이 일어날 수 있음 

 

 

 

실행 파일

브라우저를 닫지 않는 이상 생성 시간은 그대로 F5 하면 

마지막 접속 시간만 바뀐다 

 

페이지로 이동하면 

 

 

10초가 지나면

 

 

 

아까의 주의 사항! 

session을 생성해도 키값에 password 말고 userid를 넣는다면?아까 쓴 값으로 덮어쓰기 함

 

 

 

 

사용할지는 모르겠지만 세션 무효화 

 

 


 

JSP Hit Count

 

 

get을 쓰는 이유 : 다시 방문했을 때 카운트를 읽어주려고

미래를 보고 만든 코드임 

 

첫방문

 

새로고침하면 

 

재방문

 

 


 

이미지 파일 업로드 

 

 

fileUploadForm.jsp

 

라이브러리 다운 받기

 

 

실행화면

 

fileUploadForm.jsp

 

fileUploadForm.jsp

 

uploadFile.jsp

 

 

 

이미지 파일 실행

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
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
글 보관함