쿠키, 세션

Study/JSP 2012. 9. 7. 11:36

출처 - http://java-school.net/jsp/cookie_session.php

쿠키

쿠키란 웹 브라우저에 저장되는 간단한 데이터를 말한다.
웹 브라우저는 쿠키를 구어준 사이트의 자원에 요청할 때마다 쿠키 데이터를 함께 전송한다.

쿠키가 설정되는 과정

  1. 쿠키를 굽는 코드가 있는 웹 페이지 요청
  2. HTTP 응답 헤더에 쿠키 값을 설정됨
  3. 웹 브라우저는 응답 헤더에 담겨져 전달된 쿠키 데이터를 쿠키 저장소에 저장
  4. 쿠키를 구어준 웹 사이트의 다른 자원을 요청할 때마다 쿠키 데이터도 함께 전송
2번 과정에서 응답 헤더에 포함된 쿠키 값은 아래와 같은 문자열이다.
Set-Cookie: name=VALUE; expires=DATE; path=PATH; domain=DOMAIN_NAME; secure
4번 과정에서 요청 헤더에 포함된 쿠키 정보는 아래와 같은 문자열이다.
Cookie: name1=VALUE1; name2=VALUE2;...
위에서 이탤릭체로 된 부분은 실제 값으로 변경되어야 하는 부분이다.

쿠키의 구성

  • 이름: name
  • 값: value
  • 유효기간: expires
  • 도메인: domain
  • 경로: path
  • 시큐어 웹 여부(https): secure

javax.servlet.http.Cookie 클래스

생성자: Cookie(String name, String value)
getName()
setValue(String), getValue()
setDomain(String), getDomain()
setPath(String), getPath()
setMaxAge(int), getMaxAge()
setSecure(boolean), getSecure()
Cookie cookie = new Cookie("member", "superman");
cookie.setDomain(".naver.com");//점으로 시작되는 경우 관련도메인에 모두 쿠키를 전송

cookie.setPath("/");// "/"로 설정하면 웹사이트 모든 경로에 쿠키를 전송
// "/user" 와 같이 특정 경로를 설정하면 
//이 쿠키는 /user 경로에 있는 자원을 요청할 때만 쿠키를 전송

cookie.setMaxAge(60*60);//쿠키 유효기간을 1시간으로 설정
//쿠키를 설정할 때 setMaxAge 메소드를 사용하여 
//expires 부분이 있는 경우에는 웹 브라우저가 쿠키 저장소에 쿠키 데이터를 저장하고
//그렇지 않은 경우는 저장하지 않는다.
//저장소에 저장되지 않는 쿠키는 웹 브라우저가 종료할 때까지 유효하다.  



쿠키를 이용한 로그인 예제

scott 계정에 회원 테이블을 아래와 같이 작성한다.
CREATE TABLE member (
	email varchar2(60) PRIMARY KEY,
	passwd varchar2(20) NOT NULL,
	name varchar2(20) NOT NULL,
	mobile varchar2(20),
	signdate date
);
자바 빈즈을 아래와 같이 작성한다.
User.java
package com.sbsart.user;

import java.util.Date;

public class User {
	private String email;
	private String passwd;
	private String name;
	private String mobile;
	private Date signdate;
	
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getPasswd() {
		return passwd;
	}
	public void setPasswd(String passwd) {
		this.passwd = passwd;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getMobile() {
		return mobile;
	}
	public void setMobile(String mobile) {
		this.mobile = mobile;
	}
	public Date getSigndate() {
		return signdate;
	}
	public void setSigndate(Date signdate) {
		this.signdate = signdate;
	}

}
UserDAO.java
package com.sbsart.user;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDAO {
	private static final String URL = "jdbc:oracle:thin:@127.0.0.1:1521:XE";
	private static final String USER = "scott";
	private static final String PASSWORD = "tiger";
	
	public UserDAO() {
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	private Connection getConnection() throws SQLException {
		Connection con = DriverManager.getConnection(URL, USER, PASSWORD);
		return con;
	}

	private void close(ResultSet rs, PreparedStatement pstmt, Connection con) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		if (pstmt != null) {
			try {
				pstmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		if (con != null) {
			try {
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	/*
	 * 회원가입
	 */
	public void addUser(User user) {
		Connection con = null;
		PreparedStatement pstmt = null;
		//순서 email, passwd, name, mobile
		String sql = "INSERT INTO member VALUES (?, ?, ?, ?, sysdate)";

		try {
			con = getConnection();
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, user.getEmail());
			pstmt.setString(2, user.getPasswd());
			pstmt.setString(3, user.getName());
			pstmt.setString(4, user.getMobile());
			pstmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
			System.err.println(sql);
		} finally {
			close(null, pstmt, con);
		}
	}
	
	/*
	 * 로그인(쿠키예제)
	 */
	public boolean isUser(User user) {
		boolean check = false;
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = "SELECT * FROM member WHERE email=? AND passwd=?";
		try {
			con = getConnection();
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, user.getEmail());
			pstmt.setString(2, user.getPasswd());
			rs = pstmt.executeQuery();
			if (rs.next()) {
				check = true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			close(rs, pstmt, con);
		}
		
		return check;
	
	}
	
	/*
	 * 로그인(세션예제)
	 */
	public User login(User user) {
		User you = null;
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		// email,name,mobile,signdate
		String sql = "SELECT email,name,mobile FROM member WHERE email = ? AND passwd=?";
		try {
			con = getConnection();
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, user.getEmail());
			pstmt.setString(2, user.getPasswd());
			rs = pstmt.executeQuery();
			if (rs.next()) {
				you = new User();
				you.setEmail(rs.getString("email"));
				you.setMobile(rs.getString("mobile"));
				you.setName(rs.getString("name"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			close(rs, pstmt, con);
		}
		
		return you;
	}

}
다음은 JSP 페이지를 작성한다.
login.jsp, signUpForm.jsp, signUpProc.jsp, login_proc.jsp, loginConfirm.jsp, logout.jsp 를 cookie 디렉토리 아래에 다음과 같이 작성한다.
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>로그인</title>
</head>
<body>
<h1>로그인</h1>
<form action="login_proc.jsp" method="post">
	<p style="magin: 0;padding: 0;">
	email <input type="text" name="email" /><br />
	패스워드 <input type="password" name="passwd" /><br />
	<input type="submit" value="로그인" /><br />
	<input type="button" value="회원가입" onclick="location.href='signUpForm.jsp'" />
	</p>
</form>
</body>
</html>
signUpForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>회원가입</title>
<script type="text/javascript">
//<![CDATA[
	function check() {
		var form = document.getElementById("signUpForm");
		var passwd = form.passwd.value;
		var confirm = form.confirm.value;
		if (passwd == '') return;
		if (passwd != confirm) {
			return;
		}
		form.submit();
	}
        
//]]>
</script>           
</head>
<body>
<h1>회원가입</h1>
<form id="signUpForm" action="signUpProc.jsp" method="post" onsubmit="check();return false;">
<p>
	이메일 <input type="text" name="email" /><br />
	이름 <input type="text" name="name" /><br />
	패스워드 <input type="text" name="passwd" /><br />
	패스워드 확인 <input type="text" name="confirm" /><br />
	핸드폰 <input type="text" name="mobile" /><br />
	<input type="submit" value="확인" />
</p>
</form>
</body>
</html>
signUpProc.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="com.sbsart.user.*" %>
<%
	request.setCharacterEncoding("UTF-8");
	String email = request.getParameter("email");
	String passwd = request.getParameter("passwd");
	String name = request.getParameter("name");
	String mobile = request.getParameter("mobile");
	
	User user = new User();
	user.setEmail(email);
	user.setPasswd(passwd);
	user.setName(name);
	user.setMobile(mobile);
	
	UserDAO dao = new UserDAO();
	dao.addUser(user);
	
	response.sendRedirect("login.jsp");
%>
login_proc.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="com.sbsart.user.*" %>
<%
	String email = request.getParameter("email");
	String passwd = request.getParameter("passwd");
	User user = new User();
	user.setEmail(email);
	user.setPasswd(passwd);
	
	UserDAO dao = new UserDAO();
	boolean check = dao.isUser(user);
	if (check) {
		Cookie cookie = new Cookie("email", email);
		response.addCookie(cookie);
		response.sendRedirect("loginConfirm.jsp");
	} else {
		response.sendRedirect("login.jsp");
	}
%>
loginConfirm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="com.sbsart.user.*" %>
<%
	String email = null;
	Cookie[] cookies = request.getCookies();
	for (int i = 0; i < cookies.length; i++) {
		if (cookies[i].getName().equals("email")) {
			email = cookies[i].getValue();
		}
	}
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>로그인 확인</title>
</head>
<body>
<p>
<%=email %>님이 로그인한 상태입니다.<br />
<input type="button" value="로그아웃" onclick="location.href='logout.jsp'" />
</p>
</body>
</html>
logout.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	boolean chk = false;
	String email = null;
	Cookie[] cookies = request.getCookies();
	for (int i = 0; i < cookies.length; i++) {
		if (cookies[i].getName().equals("email")) {
			email = cookies[i].getValue();
			chk = true;
			break;
		}
	}
	if (chk) {
		Cookie cookie = new Cookie("email", "");
		cookie.setMaxAge(0);
		response.addCookie(cookie);
	}
	
	response.sendRedirect("login.jsp");
	
%>

세션을 이용한 로그인 예제

위 예제를 세션을 이용하는 것으로 변경해 본다.
지금까지 작성한 모든 JSP 페이지를 복사하여 최상위 디렉토리 아래 session 이란 디렉토리에 위치시킨다.
먼저 login_proc.jsp, 와 loginConfirm.jsp 를 아래처럼 변경한 다음 테스트한다.
login_proc.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="com.sbsart.user.*" %>
<%
	String email = request.getParameter("email");
	String passwd = request.getParameter("passwd");
	User user = new User();
	user.setEmail(email);
	user.setPasswd(passwd);
	
	UserDAO dao = new UserDAO();
	user = dao.login(user);
	if (user != null) {
		session.setAttribute("user", user);
		response.sendRedirect("loginConfirm.jsp");
	} else {
		response.sendRedirect("login.jsp");
	}
%>
loginConfirm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="com.sbsart.user.*" %>
<%
	User user = (User)session.getAttribute("user");
	if (user == null) {
		response.sendRedirect("login.jsp");
		return;
	}
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>로그인 확인</title>
</head>
<body>
<p>
<%=user.getName() %>님이 로그인한 상태입니다.<br />
<%=user.getEmail() %><br />
<%=user.getMobile() %><br />
<br />
<input type="button" value="로그아웃" onclick="location.href='logout.jsp'" /><br />
<input type="button" value="회원정보수정" onclick="location.href='modifyUser.jsp'" /><br />
<input type="button" value="비밀번호변경" onclick="location.href='changePassword.jsp'" /><br />
<input type="button" value="회원탈퇴" onclick="location.href='byebye.jsp'" /><br />
</p>
</body>
</html>
로그아웃,회원정보변경,비밀번호변경,회원탈퇴를 차례로 구현한다.
먼저 UserDAO.java 에 아래 메소드를 추가한다.
UserDAO.java
	public int modifyUser(User user) {
		int chk = -1;
		String sql = "UPDATE member SET name=?,mobile=? WHERE email=?";
		Connection con = null;
		PreparedStatement pstmt = null;
		try {
			con = getConnection();
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, user.getName());
			pstmt.setString(2, user.getMobile());
			pstmt.setString(3, user.getEmail());
			chk = pstmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			close(null, pstmt, con);
		}
		
		return chk;
	}
	
	public int changePassword(User user) {
		int chk = -1;
		String sql = "UPDATE member SET passwd=? WHERE email=?";
		Connection con = null;
		PreparedStatement pstmt = null;
		try {
			con = getConnection();
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, user.getPasswd());
			pstmt.setString(2, user.getEmail());
			chk = pstmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			close(null, pstmt, con);
		}
		
		return chk;
	}
	
	public int byebye(User user) {
		int chk = -1;
		String sql = "DELETE FROM member WHERE email=?";
		Connection con = null;
		PreparedStatement pstmt = null;
		try {
			con = getConnection();
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, user.getEmail());
			chk = pstmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			close(null, pstmt, con);
		}
		return chk;
	}

logout.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
session.removeAttribute("user");
response.sendRedirect("login.jsp");
%>
modifyUser.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>회원정보수정</title>
</head>
<body>
<h1>회원정보수정</h1>
<form action="modifyUserProc.jsp" method="post">
	<p style="magin: 0;padding: 0;">
	이름 <input type="text" name="name" /><br />
	모바일 <input type="text" name="mobile" /><br />
	<input type="submit" value="수정" /><br />
	</p>
</form>
</body>
</html>
modifyUserProc.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="com.sbsart.user.*" %>
<%
	User user = (User) session.getAttribute("user");
	if (user == null) {
		response.sendRedirect("login.jsp");
		return;
	}
	
	request.setCharacterEncoding("UTF-8");
	String name = request.getParameter("name");
	String mobile = request.getParameter("mobile");
	
	String email = user.getEmail();
	User me = new User();
	me.setEmail(email);
	me.setName(name);
	me.setMobile(mobile);
	
	UserDAO dao = new UserDAO();
	int chk = -1;
	chk = dao.modifyUser(me);
	if (chk == 1) {
		session.setAttribute("user", me);
		response.sendRedirect("loginConfirm.jsp");
	} else {
		response.sendRedirect("modifyUser.jsp");
	}
%>
changePassword.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>비밀번호 변경</title>
<script type="text/javascript">
//<![CDATA[
	function check() {
		var form = document.getElementById("changePasswordForm");
		var passwd = form.passwd.value;
		var confirm = form.confirm.value;
		if (passwd == '') return;
		if (passwd != confirm) {
			return;
		}
		form.submit();
	}
        
//]]>
</script>           
</head>
<body>
<form id="changePasswordForm" action="changePasswordProc.jsp" method="post" onsubmit="check();return false;">
	<p style="margin; 0; padding: 0;">
	비밀번호 <input type="password" name="passwd" /><br />
	비밀번호 확인 <input type="password" name="confirm" /><br />
	<input type="submit" value="수정" />
	</p>
</form>
</body>
</html>
changePasswordProc.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="com.sbsart.user.*" %>
<%
User user = (User) session.getAttribute("user");
if (user == null) {
	response.sendRedirect("login.jsp");
	return;
}

String passwd = request.getParameter("passwd");
String email = user.getEmail();

user = new User();
user.setEmail(email);
user.setPasswd(passwd);

UserDAO dao = new UserDAO();
int chk = -1;
chk = dao.changePassword(user);
if (chk == 1) {
	response.sendRedirect("loginConfirm.jsp");
} else {
	response.sendRedirect("changePassword.jsp");
}
%>
byebye.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="com.sbsart.user.*" %>
<%
	User user = (User) session.getAttribute("user");
	if (user == null) {
		response.sendRedirect("login.jsp");
		return;
	}
	
	UserDAO dao = new UserDAO();
	int chk = -1;
	chk = dao.byebye(user);
	if (chk == 1) {
		session.removeAttribute("user");
		response.sendRedirect("login.jsp");
	} else {
		response.sendRedirect("loginConfirm.jsp");
	}
%>



'Study > JSP' 카테고리의 다른 글

[SVN] 오류 Attempted to lock an already-locked dir 해결방안  (0) 2012.11.13
숫자를 영어로 바꾸기  (0) 2012.09.21
액션  (0) 2012.06.19
스크립팅 원소  (0) 2012.06.19
지시어  (0) 2012.06.19
Posted by 코딩하는 야구쟁이
,