오늘이라도
[Web] 28. 회원 관리 & 게시판 만들기 ③ : 회원 목록, 회원 정보 상세 보기, 회원 삭제 구현 본문
취업성공패키지 SW 개발자 교육/Web
[Web] 28. 회원 관리 & 게시판 만들기 ③ : 회원 목록, 회원 정보 상세 보기, 회원 삭제 구현
upcake_ 2020. 6. 17. 14:05반응형
https://github.com/upcake/Class_Examples
교육 중에 작성한 예제들은 깃허브에 올려두고 있습니다.
gif 파일은 클릭해서 보는 것이 정확합니다.
- 회원 관리 & 게시판 만들기 ③ : 회원 목록, 회원 정보 상세 보기, 회원 삭제 구현 -
package com.member.action;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
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 com.commons.action.Action;
import com.commons.action.ActionForward;
@WebServlet("/MemberFrontController.me")
public class MemberFrontController extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String uri = request.getRequestURI();
String context = request.getContextPath();
String command = uri.substring(context.length());
//System.out.println(command); //콘솔 창에 /memberLogin.me 등이 출력된다.
Action action = null;
ActionForward forward = null;
if(command.equals("/memberLogin.me")) {
forward = new ActionForward();
forward.setPath("member/loginForm.jsp");
forward.setRedirect(false);
} else if(command.equals("/memberLoginAction.me")) {
action = new MemberLoginAction();
forward = action.execute(request, response);
} else if(command.equals("/memberJoin.me")) {
forward = new ActionForward();
forward.setPath("member/joinForm.jsp");
forward.setRedirect(false);
} else if(command.equals("/memberJoinAction.me")) {
action = new MemberJoinAction();
forward = action.execute(request, response);
} else if(command.equals("/memberLogout.me")) {
action = new MemberLogoutAction();
forward = action.execute(request, response);
} else if(command.equals("/memberListAction.me")) {
action = new MemberListAction();
forward = action.execute(request, response);
} else if(command.equals("/memberDeleteAction.me")) {
action = new MemberDeleteAction();
forward = action.execute(request, response);
} else if(command.equals("/memberViewAction.me")) {
action = new MemberViewAction();
forward = action.execute(request, response);
}
if(forward != null) {
if(forward.isRedirect()) { //true : sendRedirect() 전환
response.sendRedirect(forward.getPath());
} else { //false : forward() 전환
RequestDispatcher rd = request.getRequestDispatcher(forward.getPath());
rd.forward(request, response);
}
}
}
}
▲MemberFrontController.java
package com.member.action;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.commons.action.Action;
import com.commons.action.ActionForward;
import com.member.study.MemberDAO;
import com.member.study.MemberDTO;
public class MemberJoinAction implements Action{
@Override
public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
//String member_id = request.getParameter("member-id");
MemberDTO dto = new MemberDTO();
dto.setMember_id(request.getParameter("member_id"));
dto.setMember_pw(request.getParameter("member_pw"));
dto.setMember_name(request.getParameter("member_name"));
dto.setMember_age(Integer.parseInt(request.getParameter("member_age")));
dto.setMember_gender(request.getParameter("member_gender"));
dto.setMember_email(request.getParameter("member_email"));
MemberDAO dao = new MemberDAO();
boolean result = dao.joinMember(dto);
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
if(result == false) {
out.println("<script>alert('회원가입 실패!');");
out.println("location.href='memberJoin.me';</script>");
return null;
} else {
out.println("<script>alert('회원가입 성공!');");
out.println("location.href='memberLogin.me';</script>");
return null;
}
}
}
▲MemberJoinAction.java
- 회원가입에 성공하면 알림창이 뜨도록 변경되었다.
package com.member.action;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.commons.action.Action;
import com.commons.action.ActionForward;
import com.member.study.MemberDAO;
import com.member.study.MemberDTO;
public class MemberListAction implements Action {
@Override
public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
String id = (String) session.getAttribute("id");
ActionForward forward = new ActionForward();
if(id == null) { //ID체크 후 없으면 로그인 화면으로
forward.setPath("memberLogin.me");
forward.setRedirect(true);
return forward;
} else if(!id.equals("admin")) { //어드민이 아니면 게시글 목록 화면으로
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<script>alert('관리자가 아닙니다!');");
out.println("location.href='boardList.bo';</script>");
return null;
} else { //관리자 계정이라면
/*
//제대로 접근되는지 확인
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<script>alert('관리자로 로그인 하셨습니다!');</script>");
*/
MemberDAO dao = new MemberDAO();
ArrayList<MemberDTO> list = new ArrayList<>();
list = dao.getAllMember();
request.setAttribute("list", list);
forward.setPath("member/member_list.jsp");
forward.setRedirect(false);
return forward;
}
}
}
▲MemberListAction.java
package com.member.study;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
public class MemberDAO {
private Connection conn;
private PreparedStatement ps;
private ResultSet rs;
//DB 접속
public Connection getConn() {
String url = "jdbc:oracle:thin:@127.0.0.1:1521:XE";
String user = "hanul";
String password = "0000";
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
e.printStackTrace();
System.out.println("getConn() Exception!!!");
}
return conn;
} //getConn()
//joinMember : 회원가입
public boolean joinMember(MemberDTO dto) {
//① 접속
conn = getConn();
//② SQL 문장 작성
String sql = "INSERT INTO boardMember VALUES (?, ?, ?, ?, ?, ?)";
int succ = 0;
//③ try-catch 블록 작성 후 PreapareStatement 설정
try {
ps = conn.prepareStatement(sql);
ps.setString(1, dto.getMember_id());
ps.setString(2, dto.getMember_pw());
ps.setString(3, dto.getMember_name());
ps.setInt(4, dto.getMember_age());
ps.setString(5, dto.getMember_gender());
ps.setString(6, dto.getMember_email());
succ = ps.executeUpdate();
if(succ != 0) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("joinMember() Exception!!!");
} finally {
dbClose();
}
return false;
} //joinMember()
//isMember : 회원 여부
public int isMember(MemberDTO dto) {
conn = getConn();
String sql = "SELECT member_pw FROM boardMember WHERE member_id = ?";
int result = -1;
try {
ps = conn.prepareStatement(sql);
ps.setString(1, dto.getMember_id());
rs = ps.executeQuery();
if(rs.next()) { //아이디 존재
if(rs.getString("member_pw").equals(dto.getMember_pw())) {
result = 1; //비밀번호 일치
} else {
result = 0; //비밀번호 불일치
}
} else { //아이디가 존재하지 않는다
result = -1;
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("isMember() Exception!!!");
} finally {
dbClose();
}
return result;
} //isMember()
//전체 회원 검색
public ArrayList<MemberDTO> getAllMember() {
conn = getConn();
String sql = "SELECT * FROM boardMember";
ArrayList<MemberDTO> list = new ArrayList<>();
try {
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()) {
//하나씩 받아오는 방법도 있다.
//String member_id = rs.getString("member_id");
MemberDTO dto = new MemberDTO();
dto.setMember_id(rs.getString("member_id"));
dto.setMember_pw(rs.getString("member_pw"));
dto.setMember_name(rs.getString("member_name"));
dto.setMember_age(rs.getInt("member_age"));
dto.setMember_gender(rs.getString("member_gender"));
dto.setMember_email(rs.getString("member_email"));
list.add(dto);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("getAllMember() Exception!!!");
} finally {
dbClose();
}
return list;
} //getAllMember()
//회원 삭제
public void deleteMember(String member_id) {
conn = getConn();
String sql = "DELETE FROM boardMember WHERE member_id = ?";
try {
ps = conn.prepareStatement(sql);
ps.setString(1, member_id);
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
System.out.println("deleteMember() Exception!!!");
} finally {
dbClose();
}
} //deleteMember()
//특정 회원 검색
public MemberDTO getDetailMember(String member_id) {
conn = getConn();
String sql = "SELECT * FROM boardMember WHERE member_id = ?";
MemberDTO dto = null;
try {
ps = conn.prepareStatement(sql);
ps.setString(1, member_id);
rs = ps.executeQuery();
if(rs.next()) {
dto = new MemberDTO();
dto.setMember_id(rs.getString("member_id"));
dto.setMember_pw(rs.getString("member_pw"));
dto.setMember_name(rs.getString("member_name"));
dto.setMember_age(rs.getInt("member_age"));
dto.setMember_gender(rs.getString("member_gender"));
dto.setMember_email(rs.getString("member_email"));
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("getDetailmember() Exception!!!");
} finally {
dbClose();
}
return dto;
} //getDetailMember()
//DB 종료
public void dbClose() {
try {
if(rs != null) rs.close();
if(ps != null) ps.close();
if(conn != null) conn.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println("dbClose() Exception!!!");
}
} //dbClose()
} //class
▲MemberDAO.java
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
String id = (String) session.getAttribute("id"); //JSP는 session이 내장 객체라 바로 사용 가능하다.
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>board list JSP</title>
<script type="text/javascript">
function fnModify(id) {
alert("id : " + id);
}
</script>
</head>
<body>
<div align="center">
<h3>[자유 게시판]</h3>
<table>
<tr align="right">
<td>
<%if(id != null && id.equals("admin")) { %>
<input type="button" value="회원 관리" onclick="location.href='memberListAction.me'" />
<%} %>
<input type="button" value="로그아웃" onclick="location.href='memberLogout.me'"/>
<input type="button" value="글쓰기" onclick="location.href='boardWrite.bo'" />
<input type="button" value="회원 정보 수정" onclick="fnModify('<%=id%>')"/>
</td>
</tr>
</table>
</div>
</body>
</html>
▲board_list.jsp
<%@page import="com.member.study.MemberDTO"%>
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core" %>
<%
ArrayList<MemberDTO> list = (ArrayList<MemberDTO>)request.getAttribute("list");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>member_list JSP</title>
<script type="text/javascript">
function fnDelete(member_id) {
if(confirm("정말 삭제하시겠습니까?")) {
location.href='memberDeleteAction.me?member_id=' + member_id;
}
}
</script>
</head>
<body>
<div align="center">
<h3>[전체 회원 목록]</h3>
<table border="1">
<tr>
<th>아이디</th>
<th>이름</th>
<th>삭제</th>
</tr>
<core:forEach var="i" items="${list }">
<tr>
<td><a href="memberViewAction.me?member_id=${i.member_id }">${i.member_id }</a></td>
<td>${i.member_name }</td>
<td align="center">
<core:if test="${i.member_id eq 'admin' }">삭제 금지</core:if>
<core:if test="${i.member_id ne 'admin' }">
<input type="button" value="삭제" onclick="fnDelete('${i.member_id }')" />
</core:if>
</td>
</tr>
</core:forEach>
<tr>
<td colspan="3">
<input type="button" value="로그아웃" onclick="location.href='memberLogout.me'" />
<input type="button" value="게시판으로 이동" onclick="location.href='boardList.bo'"/>
</td>
</tr>
</table>
</div>
</body>
</html>
▲member_list.jsp
package com.member.action;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.commons.action.Action;
import com.commons.action.ActionForward;
import com.member.study.MemberDAO;
import com.member.study.MemberDTO;
public class MemberDeleteAction implements Action {
@Override
public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
String id = (String) session.getAttribute("id");
ActionForward forward = new ActionForward();
if(id == null) { //ID체크 후 없으면 로그인 화면으로
forward.setPath("memberLogin.me");
forward.setRedirect(true);
return forward;
} else if(!id.equals("admin")) { //어드민이 아니면 게시글 목록 화면으로
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<script>alert('관리자가 아닙니다!');");
out.println("location.href='boardList.bo';</script>");
return null;
} else { //관리자 계정이라면
/*
//제대로 접근되는지 확인
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<script>alert('관리자로 로그인 하셨습니다!');</script>");
*/
request.setCharacterEncoding("utf-8");
String member_id = request.getParameter("member_id");
MemberDAO dao = new MemberDAO();
dao.deleteMember(member_id);
forward.setPath("memberListAction.me");
forward.setRedirect(true);
return forward;
}
}
}
▲MemberDeleteAction.java
package com.member.action;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.commons.action.Action;
import com.commons.action.ActionForward;
import com.member.study.MemberDAO;
import com.member.study.MemberDTO;
public class MemberViewAction implements Action {
@Override
public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
String id = (String) session.getAttribute("id");
ActionForward forward = new ActionForward();
if(id == null) { //ID체크 후 없으면 로그인 화면으로
forward.setPath("memberLogin.me");
forward.setRedirect(true);
return forward;
} else if(!id.equals("admin")) { //어드민이 아니면 게시글 목록 화면으로
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<script>alert('관리자가 아닙니다!');");
out.println("location.href='boardList.bo';</script>");
return null;
} else { //관리자 계정이라면
/*
//제대로 접근되는지 확인
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<script>alert('관리자로 로그인 하셨습니다!');</script>");
*/
request.setCharacterEncoding("utf-8");
String member_id = request.getParameter("member_id");
MemberDAO dao = new MemberDAO();
MemberDTO dto = dao.getDetailMember(member_id);
request.setAttribute("dto", dto);
forward.setPath("member/member_info.jsp");
forward.setRedirect(false);
return forward;
}
}
}
▲MemberViewAction.java
<%@page import="com.member.study.MemberDTO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
request.setCharacterEncoding("utf-8");
MemberDTO dto = (MemberDTO) request.getAttribute("dto");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>member info JSP</title>
</head>
<body>
<div align="center">
<h3>[회원 정보 상세 보기]</h3>
<table border="1">
<tr>
<th>아이디</th>
<td><%=dto.getMember_id() %></td>
</tr>
<tr>
<th>비밀번호</th>
<%
int pwLength = dto.getMember_pw().length();
String mark = dto.getMember_pw().substring(0, 2);
for(int i = 0; i < pwLength - 2; i++) {
mark += "*";
}
out.println("<td>" + mark + "</td>");
%>
</tr>
<tr>
<th>이름</th>
<td><%=dto.getMember_name() %></td>
</tr>
<tr>
<th>나이</th>
<td><%=dto.getMember_age() %></td>
</tr>
<tr>
<th>성별</th>
<td><%=dto.getMember_gender() %></td>
</tr>
<tr>
<th>이메일</th>
<%if(dto.getMember_email() == null) { %>
<td>이메일이 등록되지 않았습니다.</td>
<%} else { %>
<td><%=dto.getMember_email() %></td>
<%} %>
</tr>
<tr>
<td colspan="2" align="center">
<input type="button" value="회원 목록 보기" onclick="location.href='memberListAction.me'" />
<input type="button" value="게시판 보기" onclick="location.href='boardList.bo'" />
<input type="button" value="로그아웃" onclick="location.href='memberLogout.me'" />
</td>
</tr>
</table>
</div>
</body>
</html>
▲member_info.jsp
반응형
'취업성공패키지 SW 개발자 교육 > Web' 카테고리의 다른 글
[Web] 30. 회원 관리 & 게시판 만들기 ⑤ : 게시글 등록, 전체 글 목록 조회, 페이징 (0) | 2020.06.19 |
---|---|
[Web] 29. 회원 관리 & 게시판 만들기 ④ : 회원 정보 수정, 게시글 작성, 파일 업로드 (0) | 2020.06.18 |
[Web] 27. 회원 관리 & 게시판 만들기 ② : 로그인, 회원가입 구현 (2) | 2020.06.16 |
[Web] 26. 회원 관리 & 게시판 만들기 ① : 웹 프로젝트 생성 및 페이지 작성 전 환경 준비 (3) | 2020.06.15 |
[Web] 25. ajax 통신을 이용한 json 출력 / xml 출력 / jsp 접근 (0) | 2020.06.11 |