[JSP] 쿠키 & 빈 로그인 프로세스
01 Dec 2021 -
9 minute read
쿠키(Cookie)와 빈(Bean)을 이용한 로그인 프로세스
[전체 페이지 구성]
CookieMemberLogin.jsp
▼(form실행) ▲(로그인실패)
CookieMemeberLoginOK.jsp
+ RegisterMgr.java / DBConnectionMgr.java
▼(로그인성공)
CookieLoginConfirm.jsp
▼(로그아웃)
CookieLogOut.jsp
(로그아웃(쿠키 소멸) 후 CookieMemberLogin.jsp로 이동)
DB
create database mydb;
use mydb;
create table memlist(
uid char(10) primary key,
upw char(10),
uname char(10),
num1 int,
num2 int,
uemail char(20),
uphone char(20),
zipcode char(10),
address char(20),
job char(10)
);
insert into memlist
values
('vidv', '1234', '김준형', 941125, 1234567, 'vjun@naver.com',
'010-123-4567', 26547, '서울시 은평구', '개발자'),
('abcddd', '45456', '박동석', 901215, 1634567, 'pds@naver.com',
'010-1432-5656', 15678, '서울시 강남구', '개발자');
CookieMemberLogin.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String cookieName = ""; // CookieMemberLoginOK.jsp에서 생성한 쿠키 체크
String memberId = ""; // 쿠키에 저장된 내용을 임시 보관할 변수, 사용자의 ID가 저장됨
Cookie[] cookies = request.getCookies();
if(cookies != null){
for(int i=0; i<cookies.length; i++){
if(cookies[i].getName().equals("memID")){
cookieName = cookies[i].getName();
memberId = cookies[i].getValue();
} //if
} //for
if(!memberId.equals("")){
%>
<script>
location.href="CookieLoginConfirm.jsp";
</script>
<%
} //if
}//if
%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cookie Login</title>
<link rel="stylesheet" href="style/style.css">
</head>
<body>
<div id="wrap">
<h1>Cookie & Bean을 이용한 로그인</h1>
<form action="CookieMemberLoginOK.jsp" method="post">
<table>
<caption>LogIn</caption>
<tbody>
<tr>
<td>ID</td>
<td>
<input type="text" name="memberId" maxlength="10" autofocus>
</td>
</tr>
<tr>
<td>PW</td>
<td>
<input type="text" name="memberPw" maxlength="10">
</td>
</tr>
<tr>
<td class="btn" colspan="2">
<button>Login</button>
<button type="reset">reset</button>
</td>
</tr>
</tbody>
</table>
</form>
</div>
</body>
</html>
style/style.css
@charset "UTF-8";
body {
background-color: #EAEAEA;
}
div#wrap {
width: 500px;
padding: 10px;
margin: 20px auto;
}
h1 {
text-align: center;
}
caption {
font-size: 20px;
padding: 10px;
}
table{
width: 100%;
border: 1px solid #000;
padding: 20px;
}
table td {
font-size: 24px;
padding-left: 50px;
}
input {
padding: 10px;
}
button {
top: 16px;
padding: 6px;
}
.btn {
text-align: right;
padding-top: 10px;
}
CookieMemberLoginOK.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<jsp:useBean id="memMgr" class="pack_Login.RegisterMgr" scope="page"></jsp:useBean>
<%
String memberId = "";
String memberPw = "";
if(request.getParameter("memberId") != null){
// 데이터가 존재하고 있다면
memberId = request.getParameter("memberId");
}
if(request.getParameter("memberPw") != null){
// 데이터가 존재하고 있다면
memberPw = request.getParameter("memberPw");
}
if(memMgr.passCheck(memberId, memberPw)){
// DB에 실제 존재하는 데이터인지 체크(존재하는 회원인지 확인)
// 쿠키를 생성해 로그인을 유지시키기 위함
// 한개만 생성하면 되므로 배열 필요없음
Cookie cookie = new Cookie("memID", memberId);
response.addCookie(cookie);
%>
<script>
let memberId = '<%=memberId %>'
alert(memberId + "님 안녕하세요.");
location.href = "CookieLoginConfirm.jsp";
</script>
<%
} else{
%>
<script>
alert("아이디나 비밀번호를 확인해주세요.");
location.href = "CookieMemberLogin.jsp";
</script>
<%
}
%>
<!-- 데이터 비교하는 페이지
alert창 없으면 페이지 순식간에 지나감
CookieLoginConfirm창으로 바로 이동하는것처럼 보임 -->
pack_Login/DBConnectionMgr.java
package pack_Login;
/**
* Copyright(c) 2001 iSavvix Corporation (http://www.isavvix.com/)
*
* All rights reserved
*
* Permission to use, copy, modify and distribute this material for
* any purpose and without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all
* copies, and that the name of iSavvix Corporation not be used in
* advertising or publicity pertaining to this material without the
* specific, prior written permission of an authorized representative of
* iSavvix Corporation.
*
* ISAVVIX CORPORATION MAKES NO REPRESENTATIONS AND EXTENDS NO WARRANTIES,
* EXPRESS OR IMPLIED, WITH RESPECT TO THE SOFTWARE, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR ANY PARTICULAR PURPOSE, AND THE WARRANTY AGAINST
* INFRINGEMENT OF PATENTS OR OTHER INTELLECTUAL PROPERTY RIGHTS. THE
* SOFTWARE IS PROVIDED "AS IS", AND IN NO EVENT SHALL ISAVVIX CORPORATION OR
* ANY OF ITS AFFILIATES BE LIABLE FOR ANY DAMAGES, INCLUDING ANY
* LOST PROFITS OR OTHER INCIDENTAL OR CONSEQUENTIAL DAMAGES RELATING
* TO THE SOFTWARE.
*
*/
import java.sql.*;
import java.util.Properties;
import java.util.Vector;
/**
* Manages a java.sql.Connection pool.
*
* @author Anil Hemrajani
*/
public class DBConnectionMgr {
private Vector connections = new Vector(10);
private String _driver = "com.mysql.cj.jdbc.Driver",
_url = "jdbc:mysql://127.0.0.1:3306/myDB?useSSL=false&serverTimezone=Asia/Seoul&useUnicode=true&characterEncoding=UTF-8&allowPublicKeyRetrieval=true",
_user = "root",
_password = "1234";
private boolean _traceOn = false;
private boolean initialized = false;
private int _openConnections = 10;
private static DBConnectionMgr instance = null;
public DBConnectionMgr() {
}
/** Use this method to set the maximum number of open connections before
unused connections are closed.
*/
public static DBConnectionMgr getInstance() {
if (instance == null) {
synchronized (DBConnectionMgr.class) {
if (instance == null) {
instance = new DBConnectionMgr();
}
}
}
return instance;
}
public void setOpenConnectionCount(int count) {
_openConnections = count;
}
public void setEnableTrace(boolean enable) {
_traceOn = enable;
}
/** Returns a Vector of java.sql.Connection objects */
public Vector getConnectionList() {
return connections;
}
/** Opens specified "count" of connections and adds them to the existing pool */
public synchronized void setInitOpenConnections(int count)
throws SQLException {
Connection c = null;
ConnectionObject co = null;
for (int i = 0; i < count; i++) {
c = createConnection();
co = new ConnectionObject(c, false);
connections.addElement(co);
trace("ConnectionPoolManager: Adding new DB connection to pool (" + connections.size() + ")");
}
}
/** Returns a count of open connections */
public int getConnectionCount() {
return connections.size();
}
/** Returns an unused existing or new connection. */
public synchronized Connection getConnection()
throws Exception {
if (!initialized) {
Class c = Class.forName(_driver);
DriverManager.registerDriver((Driver) c.newInstance());
initialized = true;
}
Connection c = null;
ConnectionObject co = null;
boolean badConnection = false;
for (int i = 0; i < connections.size(); i++) {
co = (ConnectionObject) connections.get(i);
// If connection is not in use, test to ensure it's still valid!
if (!co.inUse) {
try {
badConnection = co.connection.isClosed();
if (!badConnection)
badConnection = (co.connection.getWarnings() != null);
} catch (Exception e) {
badConnection = true;
e.printStackTrace();
}
// Connection is bad, remove from pool
if (badConnection) {
connections.removeElementAt(i);
trace("ConnectionPoolManager: Remove disconnected DB connection #" + i);
continue;
}
c = co.connection;
co.inUse = true;
trace("ConnectionPoolManager: Using existing DB connection #" + (i + 1));
break;
}
}
if (c == null) {
c = createConnection();
co = new ConnectionObject(c, true);
connections.addElement(co);
trace("ConnectionPoolManager: Creating new DB connection #" + connections.size());
}
return c;
}
/** Marks a flag in the ConnectionObject to indicate this connection is no longer in use */
public synchronized void freeConnection(Connection c) {
if (c == null)
return;
ConnectionObject co = null;
for (int i = 0; i < connections.size(); i++) {
co = (ConnectionObject) connections.get(i);
if (c == co.connection) {
co.inUse = false;
break;
}
}
for (int i = 0; i < connections.size(); i++) {
co = (ConnectionObject) connections.get(i);
if ((i + 1) > _openConnections && !co.inUse)
removeConnection(co.connection);
}
}
public void freeConnection(Connection c, PreparedStatement p, ResultSet r) {
try {
if (r != null) r.close();
if (p != null) p.close();
freeConnection(c);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void freeConnection(Connection c, Statement s, ResultSet r) {
try {
if (r != null) r.close();
if (s != null) s.close();
freeConnection(c);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void freeConnection(Connection c, PreparedStatement p) {
try {
if (p != null) p.close();
freeConnection(c);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void freeConnection(Connection c, Statement s) {
try {
if (s != null) s.close();
freeConnection(c);
} catch (SQLException e) {
e.printStackTrace();
}
}
/** Marks a flag in the ConnectionObject to indicate this connection is no longer in use */
public synchronized void removeConnection(Connection c) {
if (c == null)
return;
ConnectionObject co = null;
for (int i = 0; i < connections.size(); i++) {
co = (ConnectionObject) connections.get(i);
if (c == co.connection) {
try {
c.close();
connections.removeElementAt(i);
trace("Removed " + c.toString());
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
}
private Connection createConnection()
throws SQLException {
Connection con = null;
try {
if (_user == null)
_user = "";
if (_password == null)
_password = "";
Properties props = new Properties();
props.put("user", _user);
props.put("password", _password);
con = DriverManager.getConnection(_url, props);
} catch (Throwable t) {
throw new SQLException(t.getMessage());
}
return con;
}
/** Closes all connections and clears out the connection pool */
public void releaseFreeConnections() {
trace("ConnectionPoolManager.releaseFreeConnections()");
Connection c = null;
ConnectionObject co = null;
for (int i = 0; i < connections.size(); i++) {
co = (ConnectionObject) connections.get(i);
if (!co.inUse)
removeConnection(co.connection);
}
}
/** Closes all connections and clears out the connection pool */
public void finalize() {
trace("ConnectionPoolManager.finalize()");
Connection c = null;
ConnectionObject co = null;
for (int i = 0; i < connections.size(); i++) {
co = (ConnectionObject) connections.get(i);
try {
co.connection.close();
} catch (Exception e) {
e.printStackTrace();
}
co = null;
}
connections.removeAllElements();
}
private void trace(String s) {
if (_traceOn)
System.err.println(s);
}
}
class ConnectionObject {
public java.sql.Connection connection = null;
public boolean inUse = false;
public ConnectionObject(Connection c, boolean useFlag) {
connection = c;
inUse = useFlag;
}
}
pack_Login/RegisterMgr.java
package pack_Login;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
public class RegisterMgr {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
PreparedStatement pstmt = null;
public RegisterMgr() {
try {
DBConnectionMgr pool = DBConnectionMgr.getInstance();
conn = pool.getConnection();
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
/* 실행(DB연동) 확인
* public static void main(String[] args) { System.out.println("MyDB 연동 확인"); }
*/
public boolean passCheck(String memberId, String memberPw) {
// 데이터(row) 존재 여부 확인
// = 입력한 ID, PW가 일치하는 데이터가 존재하는지 체크
boolean rowChk = false;
try {
String sql = "select count(*) as cnt from memlist where uid = '"+ memberId +"' and upw = '"+memberPw+"'";
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
if(rs != null) {
while(rs.next()) {
if(rs.getInt("cnt") > 0) {
rowChk = true;
}
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return rowChk;
}
CookieLoginConfirm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String memberId = ""; // 쿠키에 저장된 내용을 임시 보관할 변수, 사용자의 ID가 저장됨
Cookie[] cookies = request.getCookies();
if(cookies != null){
for(int i=0; i<cookies.length; i++){
if(cookies[i].getName().equals("memID")){
memberId = cookies[i].getValue();
} //if
} //for
if(memberId.equals("")){
%>
<script>
alert("로그인 페이지로 이동합니다.");
location.href="CookieMemberLogin.jsp";
</script>
<%
} //if
}//if
%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style/style.css">
</head>
<body>
<div id="wrap">
<h1>Cookie & Bean을 이용한 로그인</h1>
<table>
<caption><%=memberId %>님 로그인 상태입니다.</caption>
<tbody>
<tr>
<td>
<a href="CookieLogOut.jsp">로그아웃</a>
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
CookieLogOut.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (int i=0; i<cookies.length; i++) {
if (cookies[i].getName().equals("memID")) {
cookies[i].setMaxAge(0);
response.addCookie(cookies[i]);
} // if
} // for
%>
<script>
alert("로그아웃 되었습니다.");
location.href = "CookieMemberLogin.jsp";
</script>
<% } // if %>
실행결과
- CookieMemberLogin.jsp 파일 실행
-
CookieMemberLoginOK.jsp(+ pack_Login.RegisterMgr + DBCP)에서 데이터 확인
-
잘못된 정보(DB에 존재하지 않는 데이터)입력 시 CookieMemberLogin.jsp 파일로 다시 이동
-
CookieMemberLoginOK.jsp(+ pack_Login.RegisterMgr + DBCP)에서 데이터 확인
-
올바른 정보(DB에 존재하는 데이터)입력 시 CookieLoginConfirm.jsp 파일로 이동
- 로그아웃 클릭 시 CookieLogOut.jsp 파일로 이동 후 CookieMemberLogin.jsp로 이동