-
DAO: Data Access Object. Database의 data에 접근을 위한 객체. Database에 접근을 하기위한 로직과 비즈니스 로직을 분리하기 위해서 사용함
-
커넥션 풀: DB와 연결할때 매번 커넥션 객체를 생성하지 않고 미리 만든후 가져다 씀. 다쓰면 반환.
-
DTO(=VO): Data Transfer Object. Value Object. 계층간 데이터 교환을 위한 자바빈즈. (VO는 read only 속성을 가짐) (생성자, 게터 세터 모음을 자바빈즈라 하는군)
-
New Dinamic Web Project로 JSP_Project 생성하고 context.xml파일을 META-INF 폴더에 붙여넣기, json-simple-1.1.1.jar 파일을 WEB-INF 폴더에 붙어넣기. WebContent에 새 폴더-member 폴더 만들기
-
memberForm.jsp: 회원가입 폼
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>회원 가입</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="member.js"></script>
<style>
#container {
width:420px;
border:1px solid black;
padding:20px 40px;
margin:0 auto;
}
</style>
</head>
<body>
<div id="container">
<h2>회원 가입</h2>
'*'표시 항목은 필수 입력 항목입니다.
<p><a href="memberList.jsp">전체보기</a></p>
<hr>
<form action="memberPro.jsp" id="frm" method="post">
<input type="hidden" name="uid" id="uid">
<table>
<tr>
<td>이름</td>
<td><input type="text" name="name" id="name" size="10">*</td>
</tr>
<tr>
<td>아이디</td>
<td colspan="2">
<input type="text" name="userid" id="userid" size="20" disabled="disabled">*
<input type="button" value="중복 체크" id="idBtn"></td>
</tr>
<tr>
<td>암호</td>
<td><input type="password" name="pwd" id="pwd" size="20">*</td>
</tr>
<tr height="30">
<td width="80">암호 확인</td>
<td><input type="password" name="pwd_check" id="pwd_check" size="20">*</td>
</tr>
<tr>
<td>이메일</td>
<td><input type="text" name="email" id="email" size="20"></td>
</tr>
<tr>
<td>전화번호</td>
<td><input type="text" name="phone" id="phone" size="10"></td>
</tr>
<tr>
<td>등급</td>
<td><input type="radio" name="admin" value="0"
checked="checked">일반회원
<input type="radio" name="admin" value="1">관리자</td>
</tr>
<tr>
<td colspan="3" align="center">
<input type="button" id="send" value="확인">
<input type="reset" value="취소"></td>
</tr>
</table>
</form>
</div>
</body>
</html>
-
memberPro.jsp: 회원가입 로직
<%@page import="com.member.MemberDAOImpl"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
request.setCharacterEncoding("utf-8");
%>
<jsp:useBean id="member" class="com.member.MemberVO"/>
<jsp:setProperty property="*" name="member"/>
<%
MemberDAOImpl dao=MemberDAOImpl.getInstance();
String uid=request.getParameter("uid");
member.setUserid(uid);
dao.memberInsert(member);
response.sendRedirect("loginForm.jsp");
%>
-
member.js: 자바스크립트 파일 (jsp파일에 기입하지 않고 따로 기입)
var exp= /^[0-9]{3}-[0-9]{4}-[0-9]{4}$/;
$(document).ready(function(){
$("#send").click(function(){
if($("#name").val()==""){
alert("이름을 입력하세요");
$("#name").focus();
return false;
}
//아이디가 공백일때
if($("#userid").val()==""){
alert("아이디를 입력하세요");
$("#userid").focus();
return false;
}
//암호가 공백일때
if($("#pwd").val()==""){
alert("암호를 입력하세요");
$("#pwd").focus();
return false;
}
//암호확인이 공백일때
if($("#pwd_check").val()==""){
alert("암호확인 필수");
$("#pwd_check").focus();
return false;
}
//암호 일치확인
if($("#pwd").val()!=$("#pwd_check").val()){
alert("암호 불일치");
$("#pwd_check").focus();
return false;
}
//전화번호 확인(정규식을 만들어놓고 비교)
if(!$("#phone").val().match(exp)){
alert("전화번호를 정확하게 입력하세요");
$("#phone").focus();
return false;
}
$("#frm").submit();
});//send
//아이디 중복체크 버튼을 눌렀을때
$("#idBtn").click(function(){
window.open("idCheck.jsp","","width=600 height=500")
}); //idBtn
//중복체크 새 창에서 아이디 중복확인
$("#idCheckBtn").click(function(){
if($("#userid").val()==""){
alert("아이디를 입력하세요");
$("#userid").focus();
return false;
}
$.ajax({
type:"post",
url :"idCheckPro.jsp",
data: {"userid":$("#userid").val()},
success: function(value){
if(value.trim()=="yes"){
alert("사용가능한 아이디")
$(opener.document).find("#userid").val($("#userid").val());
$(opener.document).find("#uid").val($("#userid").val());
self.close();
}else{
alert("중복된 아이디")
}
},
error: function(e){
alert("error:"+e)
}
});
}) //idCheckBtn
})//document
function del(userid, mode){
if(mode=="관리자"){
alert("관리자는 삭제할 수 없음");
return;
}
$.getJSON("memberDelete.jsp",
{"userid": userid},
function(data){
var htmlStr="";
$.each(data,function(key,val){
htmlStr+="<tr>";
htmlStr+="<td>"+val.name+"</td>";
htmlStr+="<td>"+val.userid+"</td>";
htmlStr+="<td>"+val.phone+"</td>";
htmlStr+="<td>"+val.email+"</td>";
htmlStr+="<td>"+val.mode+"</td>";
htmlStr+="<td><a href=javascript:del('"+val.userid+"','"+val.mode+"')>삭제2</a></td>";
htmlStr+="</tr>";
})
$("table tbody").html(htmlStr);
} //콜백함수
); //getJSON
} //del() 함수
-
com.member 패키지 생성
-
MemberDAO.java: DB연결 하는 인터페이스
package com.member;
import java.util.ArrayList;
public interface MemberDAO {
//CRUD(create read update delete)라고 함
//추가 (MemberVO 형의 vo 객체를 추가)
public void memberInsert(MemberVO vo);
//전체보기 (전체리스트를 보려면? select에 들어가는 값 MemberVO 형의 ArrayList를 본다.)
public ArrayList<MemberVO>memberList();
//수정
public int memberUpdate(MemberVO vo);
//상세보기 (하나를 보려면? return값이 있다는 뜻. MemberVO형)
public MemberVO memberView(String userid);
//삭제
public void memberDel(String userid);
//아이디 중복 체크 (리턴값은 userid)
public String idCheck(String userid);
//로그인 체크 (리턴값은 flag)
public int loginCheck(String userid, String pwd);
}
-
MemberDAOImpl: DB연결 수행
package com.member;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class MemberDAOImpl implements MemberDAO{
private static MemberDAOImpl instance=new MemberDAOImpl();
public static MemberDAOImpl getInstance() {
return instance;
}
private Connection getConnection() throws Exception{
Context initCtx=new InitialContext();
Context envCtx=(Context) initCtx.lookup("java:comp/env");
DataSource ds=(DataSource) envCtx.lookup("jdbc/member"); //context.xml의 name을 jdbc/member로 바꾸기
return ds.getConnection();
}
//추가
public void memberInsert(MemberVO vo) {
Connection con=null;
PreparedStatement ps=null;
try {
con=getConnection();
String sql="INSERT INTO JMEMBER VALUES (?,?,?,?,?,?)";
ps=con.prepareStatement(sql);
ps.setString(1, vo.getUserid());
ps.setString(2, vo.getName());
ps.setString(3, vo.getPwd());
ps.setString(4, vo.getEmail());
ps.setString(5, vo.getPhone());
ps.setInt(6, vo.getAdmin());
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(con,ps);
}
}
//전체보기 List
public ArrayList<MemberVO> memberList() {
Connection con=null;
Statement st=null;
ResultSet rs=null; //결과가 있으면 ResultSet씀
ArrayList<MemberVO> arr=new ArrayList<>();
try {
con=getConnection();
String sql="SELECT * FROM JMEMBER";
st=con.createStatement();
rs=st.executeQuery(sql);
while(rs.next()) {
MemberVO member=new MemberVO();
member.setName(rs.getString("name"));
member.setUserid(rs.getString("userid"));
member.setPwd(rs.getString("pwd"));
member.setEmail(rs.getString("email"));
member.setPhone(rs.getString("phone"));
member.setAdmin(rs.getInt("admin"));
arr.add(member);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(con, st, rs);
}
return arr;
}
//일반회원 회원정보 수정
public int memberUpdate(MemberVO vo) {
Connection con=null;
PreparedStatement ps=null;
int flag=0;
try {
con=getConnection();
String sql="update JMEMBER set name=?, pwd=?, email=?, phone=?, admin=? where userid=?";
ps=con.prepareStatement(sql);
ps.setString(1, vo.getName());
ps.setString(2, vo.getPwd());
ps.setString(3, vo.getEmail());
ps.setString(4, vo.getPhone());
ps.setInt(5, vo.getAdmin());
ps.setString(6, vo.getUserid());
flag=ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(con, ps);
}
return flag;
}
//일반회원 회원정보 상세보기
public MemberVO memberView(String userid) {
Connection con=null;
Statement st=null;
ResultSet rs=null;
MemberVO m=null;
try {
con=getConnection();
String sql="select * from JMEMBER where userid='"+userid+"'";
st=con.createStatement();
rs=st.executeQuery(sql);
if(rs.next()) {
m=new MemberVO();
m.setUserid(rs.getString("userid"));
m.setPwd(rs.getString("pwd"));
m.setPhone(rs.getString("phone"));
m.setName(rs.getString("name"));
m.setEmail(rs.getString("email"));
m.setAdmin(rs.getInt("admin"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(con, st, rs);
}
return m;
}
//삭제
public void memberDel(String userid) {
Connection con=null;
Statement st=null;
try {
con=getConnection();
String sql="delete from JMEMBER where userid='"+userid+"'";
st=con.createStatement();
st.executeUpdate(sql);
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(con, st, null);
}
}
//아이디 중복체크
public String idCheck(String userid) {
Connection con=null;
Statement st=null;
ResultSet rs=null;
String flag="yes"; //사용가능
try {
con=getConnection();
String sql="select * from JMEMBER where userid='"+userid+"'";
st=con.createStatement();
rs=st.executeQuery(sql);
if(rs.next()) {
flag="no";
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(con, st, rs);
}
return flag;
}
//로그인체크 (비밀번호 오류: 2, 회원아님: -1, 관리자: 1, 일반회원: 0)
public int loginCheck(String userid, String pwd) {
Connection con=null;
Statement st=null;
ResultSet rs=null;
int flag=-1;
try {
con=getConnection();
String sql="select pwd, admin from JMEMBER where userid='"+userid+"'";
st=con.createStatement();
rs=st.executeQuery(sql);
if(rs.next()) { //id는 맞음
if(rs.getString("pwd").equals(pwd)) { //비번 맞다
flag=rs.getInt("admin");
}else { //비번 틀림
flag=2;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(con, st, rs);
}
return flag;
}
//닫기 closeConnection
private void closeConnection(Connection con, PreparedStatement ps) {
try {
if(ps!=null) ps.close();
if(con!=null) con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
private void closeConnection(Connection con, Statement st, ResultSet rs) {
try {
if(st!=null) st.close();
if(con!=null) con.close();
if(rs!=null) rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
-
MemberVO: 게터 세터 생성자. 자바빈즈
package com.member;
public class MemberVO {
private String name;
private String userid;
private String pwd;
private String email;
private String phone;
private int admin;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public int getAdmin() {
return admin;
}
public void setAdmin(int admin) {
this.admin = admin;
}
}
-
memberList.jsp: 가입된 회원목록 폼 (관리자만 볼 수 있음)
<%@page import="com.member.MemberVO"%>
<%@page import="java.util.ArrayList"%>
<%@page import="com.member.MemberDAOImpl"%>
<%@ 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>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="member.js"></script>
<style>
div.divCss{
text-align: right;
background-color: darkgray;
padding-right: 20px;
}
a:hover { text-decoration: none; }
a:link {text-decoration: none; }
a:visited {text-decoration: none; }
</style>
</head>
<div class="divCss">
<a href="memberForm.jsp">추가하기 /</a>
<a href="memberList.jsp">전체보기</a>
</div>
<%
request.setCharacterEncoding("utf-8");
MemberDAOImpl dao=MemberDAOImpl.getInstance();
ArrayList<MemberVO> arr=dao.memberList();
String suserid=(String)session.getAttribute("userid");
%>
<body>
<div align="right">
<a href="memberView.jsp"><%=suserid%></a> 관리자님 반갑습니다.
<a href="logout.jsp">로그아웃</a>
</div>
<table class="table table-striped">
<thead>
<tr>
<th scope="col">이름</th>
<th scope="col">아이디</th>
<th scope="col">전화번호</th>
<th scope="col">이메일</th>
<th scope="col">구분</th>
<th scope="col">삭제</th>
</tr>
</thead>
<tbody>
<%
for(MemberVO m:arr){
String mode=m.getAdmin()==0?"일반회원":"관리자";
%>
<tr>
<th scope="row"><%=m.getName() %></th>
<td><%=m.getUserid() %></td>
<td><%=m.getPhone() %></td>
<td><%=m.getEmail() %></td>
<td><%=mode %></td>
<td><a href="javascript:del('<%=m.getUserid() %>','<%=mode%>')">삭제</a></td>
</tr>
<%
}
%>
</tbody>
</table>
</body>
</html>
-
idCheck.jsp: 아이디 중복확인 폼
<%@ 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>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="member.js"></script>
</head>
<body>
<h2>아이디 중복확인</h2>
아이디 <input type="text" name="userid" id="userid">
<input type="button" value="사용" id="idCheckBtn">
</body>
</html>
-
idCheckPro.jsp: 아이디 중복확인 로직
<%@page import="com.member.MemberDAOImpl"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
request.setCharacterEncoding("utf-8");
MemberDAOImpl dao=MemberDAOImpl.getInstance();
String userid=request.getParameter("userid");
String flag=dao.idCheck(userid);
out.println(flag);
%>
-
loginForm.jsp: 로그인 화면 폼 (로그인, 취소, 회원가입 버튼)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>로그인</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script type="text/javascript">
$(function(){
$("#loginBtn").click(function(){
if($("#userid").val()==""){
alert("아이디를 입력하세요");
$("#userid").focus();
return false;
}
if($("#pwd").val()==""){
alert("암호를 입력하세요");
$("#pwd").focus();
return false;
}
$.ajax({
type : "post",
url : "loginPro.jsp",
data : {"userid": $("#userid").val(), "pwd": $("#pwd").val()},
success: function(value){
switch(value.trim()){
case "0" : alert("로그인 성공");
$(location).attr("href","memberView.jsp");
break;
case "1" : alert("관리자 로그인");
location.href="memberList.jsp";
break;
case "-1" : alert("회원이 아닙니다.");
break;
case "2" : alert("비밀번호 오류"); break;
default : alert(value().trim());
}
},
error : function(e){
alert("error: "+e);
}
})
}); //loginBtn
}); //document
</script>
<style>
#container {
width:250px;
border:1px solid green;
padding:20px 40px;
margin:0 auto;
}
</style>
</head>
<body>
<div id="container">
<h2>로그인</h2>
<hr>
<form>
<table>
<tr>
<td>아이디</td>
<td><input type="text" name="userid" id="userid"></td>
</tr>
<tr>
<td>암호</td>
<td><input type="password" name="pwd" id="pwd"></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="button" value="로그인" id="loginBtn">
<input type="reset" value="취소">
<input type="button" value="회원 가입" onclick="location.href='memberForm.jsp'">
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
-
loginPro.jsp: 로그인 로직. 아이디와 암호를 들고 MemberDAOImpl의 loginCheck 메소드를 연결해줌
<%@page import="com.member.MemberDAOImpl"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
request.setCharacterEncoding("utf-8");
String userid=request.getParameter("userid");
String pwd=request.getParameter("pwd");
MemberDAOImpl dao=MemberDAOImpl.getInstance();
int flag=dao.loginCheck(userid, pwd);
if (flag==0 || flag==1){
session.setAttribute("userid", userid);
}
out.println(flag);
%>
-
logout.jsp: 세션을 지우고 로그인 화면으로 이동
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
session.invalidate();
//session.removeAttribute("userid");
response.sendRedirect("loginForm.jsp");
%>
-
memberView.jsp: 일반회원이 로그인했을때 보이는 화면 폼 (회원정보 수정)
<%@page import="com.member.MemberVO"%>
<%@page import="com.member.MemberDAOImpl"%>
<%@ 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>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="member.js"></script>
</head>
<%
request.setCharacterEncoding("utf-8");
String userid=(String)session.getAttribute("userid");
MemberDAOImpl dao=MemberDAOImpl.getInstance();
MemberVO m=dao.memberView(userid);
%>
<body>
<%=userid %>님 반갑습니다. /<a href="logout.jsp">로그 아웃</a><br>
<h2>
회원정보 변경/<a href="userDelete.jsp">회원탈퇴</a>
</h2>
<hr>
<form action="updatePro.jsp" method="post">
<input type="hidden" name="userid" value="<%=userid %>">
<table>
<thead>
<tr>
<td>이름</td>
<td><input type="text" id="name" name="name" value="<%=m.getName()%>"></td>
</tr>
<tr>
<td>비밀번호</td>
<td><input type="password" id="pwd" name="pwd" value="<%=m.getPwd()%>"></td>
</tr>
<tr>
<td>이메일</td>
<td><input type="text" id="email" name="email" value="<%=m.getEmail()%>"></td>
</tr>
<tr>
<td>전화번호</td>
<td><input type="text" id="phone" name="phone" value="<%=m.getPhone()%>"></td>
</tr>
<tr>
<td>등급</td>
<td>
<input type="radio" name="admin" value="0">일반회원
<input type="radio" name="admin" value="1">관리자
<script>
if(<%=m.getAdmin()%>==0){
$("input:radio[value='0']").prop("checked", true);
}else{
$("input:radio[value='1']").prop("checked", true);
}
</script>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" id="updateBtn" value="수정">
<input type="reset" value="취소">
</tr>
</thead>
</table>
</form>
</body>
</html>
-
updatePro.jsp: 회원정보 수정 로직
<%@page import="com.member.MemberDAOImpl"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
request.setCharacterEncoding("utf-8");
%>
<jsp:useBean id="mvo" class="com.member.MemberVO"/>
<jsp:setProperty property="*" name="mvo"/>
<%
MemberDAOImpl dao=MemberDAOImpl.getInstance();
int flag=dao.memberUpdate(mvo);
if(flag==1){
session.invalidate();
response.sendRedirect("loginForm.jsp");
}
%>
-
userDelete.jsp: 회원탈퇴 로직
<%@page import="com.member.MemberDAOImpl"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
request.setCharacterEncoding("utf-8");
String userid=(String)session.getAttribute("userid");
MemberDAOImpl dao=MemberDAOImpl.getInstance();
dao.memberDel(userid);
session.invalidate();
response.sendRedirect("loginForm.jsp");
%>
-
memberDelete.jsp: 관리자로 로그인 했을때 회원들 삭제하는 로직
<%@page import="org.json.simple.JSONObject"%>
<%@page import="org.json.simple.JSONArray"%>
<%@page import="com.member.MemberVO"%>
<%@page import="java.util.ArrayList"%>
<%@page import="com.member.MemberDAOImpl"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
request.setCharacterEncoding("utf-8");
String userid=request.getParameter("userid");
MemberDAOImpl dao=MemberDAOImpl.getInstance();
dao.memberDel(userid);
ArrayList<MemberVO> arr=dao.memberList();
JSONArray jarr=new JSONArray();
for(MemberVO vo:arr){
String mode=vo.getAdmin()==0? "일반회원":"관리자";
JSONObject obj=new JSONObject();
obj.put("name", vo.getName());
obj.put("userid", vo.getUserid());
obj.put("email", vo.getEmail());
obj.put("phone", vo.getPhone());
obj.put("mode", mode);
jarr.add(obj);
}
out.println(jarr.toString());
%>
'Learning > JSP' 카테고리의 다른 글
게시판 1 (0) | 2020.07.22 |
---|---|
회원가입2 (0) | 2020.07.22 |
주소록 생성하기2 (0) | 2020.07.16 |
JSON 형식의 데이터값 읽어오기 (0) | 2020.07.15 |
ajax방식을 이용하여 id, pw 입력하고 하단부에 출력 (0) | 2020.07.15 |