오늘이라도

[Web] 29. 회원 관리 & 게시판 만들기 ④ : 회원 정보 수정, 게시글 작성, 파일 업로드 본문

취업성공패키지 SW 개발자 교육/Web

[Web] 29. 회원 관리 & 게시판 만들기 ④ : 회원 정보 수정, 게시글 작성, 파일 업로드

upcake_ 2020. 6. 18. 12:27
반응형

https://github.com/upcake/Class_Examples

교육 중에 작성한 예제들은 깃허브에 올려두고 있습니다. 

gif 파일은 클릭해서 보는 것이 정확합니다.


 - 제목회원 관리 & 게시판 만들기 ④ : 회원 정보 수정, 게시글 작성, 파일 업로드 -

▲회원 정보 수정 작동 화면

 

▲게시글 작성, 파일 업로드 작동 화면

 

▲파일 업로드 후 업로드된 파일

 

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()
	
	//비밀번호 검색
	public String getMember_pw(String id) {
		conn = getConn();
		String sql = "SELECT member_pw FROM boardMember WHERE member_id = ?";
		String member_pw = null;
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, id);
			rs = ps.executeQuery();
			
			if(rs.next()) {
				member_pw = rs.getString("member_pw");
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("getMember_pw() Exception!!!");
		} finally {
			dbClose();
		}
		return member_pw;
	} //getMember_pw()
	
	//회원 정보 수정
	public int updateMember(MemberDTO dto) {
		conn = getConn();
		String sql = "UPDATE boardMember SET member_pw = ?, member_name = ?,";
		sql += " member_age = ?, member_gender = ?, member_email = ? WHERE member_id = ?";
		int succ = 0;
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, dto.getMember_pw());
			ps.setString(2, dto.getMember_name());
			ps.setInt(3, dto.getMember_age());
			ps.setString(4, dto.getMember_gender());
			ps.setString(5, dto.getMember_email());
			ps.setString(6, dto.getMember_id());
			succ = ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("updateMember() Exception!!!");
		} finally {
			dbClose();
		}
		return succ;
	} //updateMember()
	
	//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 import="com.member.study.MemberDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
String id = (String) session.getAttribute("id"); //JSP는 session이 내장 객체라 바로 사용 가능하다.
MemberDAO dao = new MemberDAO();
String member_pw = dao.getMember_pw(id);
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>board list JSP</title>
<script type="text/javascript">
function fnModify(id, member_pw) {
	//alert("id : " + id);
	var pw = prompt("비밀번호를 입력하세요","");
	//alert("member_pw : " + member_pw + "\npw : " + pw);
	//member_pw : dto에 저장되어있던 비밀번호
	//pw : 방금 사용자로부터 입력받은 비밀번호
	if(member_pw == pw) { //맞는 비밀번호를 입력하면 URL이 바뀐다
		//alert("비밀번호 일치합니다.")
		location.href = "memberDetailAction.me?member_id=" + id;
	} else {
		alert("비밀번호가 일치하지 않습니다.");
	}
}
</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%>', '<%=member_pw %>')"/>
			</td>
		</tr>
	</table>
</div>
</body>
</html>

▲board_list.jsp

 

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);
		} else if(command.equals("/memberDetailAction.me")) {
			action = new MemberDetailAction();
			forward = action.execute(request, response);
		} else if(command.equals("/memberUpdateAction.me")) {
			action = new MemberUpdateAction();
			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 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 MemberDetailAction implements Action {
	@Override
	public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		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);
		
		ActionForward forward = new ActionForward();
		forward.setPath("member/member_detailForm.jsp");
		forward.setRedirect(false);
		return forward;
	}

}

▲MemberDetailAction.java

 

<%@page import="com.member.study.MemberDTO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
MemberDTO dto = (MemberDTO) request.getAttribute("dto");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>member detailForm JSP</title>
<script type="text/javascript">
function fnSubmit() {
	if(confirm("정말 수정하시겠습니까?")) {
		return true;
	}
	return false;
}
</script>
</head>
<body>
<div align="center">
	<h3>[회원정보 수정]</h3>
	<form action="memberUpdateAction.me" method="post" onsubmit="fnSubmit()">
	<input type="hidden" name="member_id" value="<%=dto.getMember_id() %>" />
		<table border="1">
			<tr>
				<th>아이디</th>
				<td><%=dto.getMember_id() %></td>
			</tr>
			<tr>
				<th>비밀번호</th>
				<td><input type="password" name="member_pw" value="<%=dto.getMember_pw() %>" /></td>
			</tr>
			<tr>
				<th>이름</th>
				<td><input type="text" name="member_name" value="<%=dto.getMember_name() %>" /></td>
			</tr>
			<tr>
				<th>나이</th>
				<td><input type="number" name="member_age" value="<%=dto.getMember_age() %>" /></td>
			</tr>
			<tr>
				<th>성별</th>
				<td>
					<%if(dto.getMember_gender().equals("남")) { %>
						<input type="radio" name="member_gender" value="남" checked="checked"/>남자
						<input type="radio" name="member_gender" value="여" />여자
					<%} else { %>
						<input type="radio" name="member_gender" value="남" />남자
						<input type="radio" name="member_gender" value="여" checked="checked" />여자
					<%} %>
				</td>
			</tr>
			<tr>
				<th>이메일</th>
				<td>
					<%if(dto.getMember_email() == null) { %>
						<input type="text" name="member_email" value=""/>
					<%} else {%>
						<input type="text" name="member_email" value="<%=dto.getMember_email() %>"/>
					<%} %>
				</td>
			</tr>
			<tr>
				<td colspan="2">
					<input type="submit" value="수정하기" />
					<input type="reset" value="초기화하기" />
					<input type="button" value="게시판 보기" onclick="location.href='boardList.bo'" /> 
				</td>
			</tr>
		</table>
	</form>
</div>
</body>
</html>

▲member_detailForm.jsp

 

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 MemberUpdateAction implements Action {

	@Override
	public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		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();
		int succ = dao.updateMember(dto);

		response.setContentType("text/html; charset=utf-8");
		PrintWriter out = response.getWriter();
		if (succ > 0) {
			out.println("<script>alert('수정 성공');");
			out.println("location.href='boardList.bo'</script>");
		} else {
			out.println("<script>alert('수정 실패');");
			out.println("location.href='boardList.bo'</script>");
		}
		return null;
	}
}

▲MemberUpdateAction.java

 

package com.board.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("/BoardFrontController.bo")
public class BoardFrontController 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("/boardList.bo")) {
			action = new BoardListAction();
			forward = action.execute(request, response);
		} else if(command.equals("/boardWrite.bo")) {
			forward = new ActionForward();
			forward.setPath("board/board_write.jsp");
			forward.setRedirect(false);
			//가져갈게 있으면 true(forward) 없으면 false(sendRedirect)
			//URL 바뀌면 true(boardWrite.bo로 바뀌어서 안됨) 안바뀌면 false
		} else if(command.equals("/boardAddAction.bo")) {
			action = new BoardAddAction();
			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);
			}
		}
	}
}

▲BoardFrontController.java

 

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
String id = (String) session.getAttribute("id");
if(id == null) {
	response.sendRedirect("memberLogin.me");
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>board write jsp</title>
<script type="text/javascript">
function fnSubmit() {
	if(confirm("작성하신 글을 등록하시겠습니까?")) {
		return true;
	}
	return false;
}
</script>
</head>
<body>
<div align="center">
	<h3>[게시판 글쓰기]</h3>
	<form action="boardAddAction.bo" method="post" enctype="multipart/form-data" onsubmit="return fnSubmit()">
	<!-- enctype : 파일 첨부할때 필요한 속성 -->
	<input type="hidden" name="board_id" value="<%=id %>" />
		<table border="1">
			<tr>
				<th>작성자</th>
				<td><%=id %></td>
			</tr>
			<tr>
				<th>제목</th>
				<td><input type="text" name="board_subject" maxlength="50" required="required"/></td>
			</tr>
			<tr>
				<th>내용</th>
				<td><textarea rows="15" cols="70" name="board_content"></textarea></td>
			</tr>
			<tr>
				<th>파일 첨부</th>
				<td><input type="file" name="board_file" /></td>
			</tr>
			<tr>
				<td colspan="2" align="center">
					<input type="submit" value="글 등록" />
					<input type="reset" value="다시 작성" />
					<input type="button" value="목록 보기" onclick="location.href='boardList.bo'"/>
				</td>
			</tr>
		</table>
	</form>
</div>
</body>
</html>

▲board_write.jsp

반응형