-
26. Model2 방식 - 회원개발자 수업/JSP 2021. 12. 22. 16:28
1. 회원 관련 추가 기능
1) 커맨드(Command) 패턴
- 브라우저가 URL 패턴을 이용해 Controller에게 수행 작업을 request하는 방법
- getPathInfo() 이용해 요청명을 받아와 작업을 수행
2) http://localhost:8080/chap20_model2/member/listMembers.do
http://localhost:8080/chap20_model2/member/editMembers.do
http://localhost:8080/chap20_model2/member/updateMembers.do
2. 회원 등록
3. 회원 정보 수정
1) 회원 정보 수정창에서 회원 정보를 수정하고 수정하기를 클릭해 /member/modMember.do로 Controller에 요청
2) Controller는 전송된 수정 정보를 가져온 후 테이블에서 회원 정보를 수정(update)
3) 수정을 마친 후 컨트롤러는 다시 회원 목록창을 표시
MemberController.java package kr.co.ezenac.member02; import java.io.IOException; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class MemberController * 브라우저에서 요청시 두 단계로 요청이 이루어짐 */ @WebServlet(name = "MemberController2", urlPatterns = { "/member/*" }) public class MemberController extends HttpServlet { private static final long serialVersionUID = 1L; MemberDAO memberDAO; /** * @see Servlet#init(ServletConfig) */ public void init(ServletConfig config) throws ServletException { memberDAO = new MemberDAO(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doHandle(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doHandle(request, response); } private void doHandle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String forwardPage = null; request.setCharacterEncoding("utf-8"); response.setContentType("text/html; charset=utf-8"); String action = request.getPathInfo(); //URL에서 요청명을 가져옴 System.out.println("getPathInfo() : " + action); //최초 요청이거나 action 값이 /listmembers.do면 회원목록을 출력함 if(action == null || action.equals("/listmembers.do")) { List<MemberVO> membersList = memberDAO.listMembers(); request.setAttribute("membersList", membersList); forwardPage = "/member02/listmembers.jsp"; //member02 폴더의 listmembers.jsp로 포워딩 } else if(action.equals("/addMember.do")) { String id = request.getParameter("id"); String pwd = request.getParameter("pwd"); String name = request.getParameter("name"); String email = request.getParameter("email"); MemberVO memberVO = new MemberVO(id, pwd, name, email); memberDAO.addMember(memberVO); forwardPage = "/member/listmembers.do"; } else if(action.equals("/memberForm.do")) { forwardPage = "/member02/memberForm.jsp"; } else if(action.equals("/modMemberForm.do")) { String id = request.getParameter("id"); MemberVO memInfo = memberDAO.findMember(id); request.setAttribute("memInfo", memInfo); forwardPage = "/member02/modMemberForm.jsp"; } else if(action.equals("/modMember.do")) { String id = request.getParameter("id"); String pwd = request.getParameter("pwd"); String name = request.getParameter("name"); String email = request.getParameter("email"); MemberVO memberVO = new MemberVO(id, pwd, name, email); memberDAO.modMember(memberVO); request.setAttribute("msg", "modified"); forwardPage = "/member/listmembers.do"; } else if(action.equals("/delMember.do")) { String id = request.getParameter("id"); memberDAO.delMember(id); request.setAttribute("msg", "deleted"); forwardPage = "/member/listmembers.do"; } else { //그 외 다른 action 값은 회원 목록 출력 List<MemberVO> membersList = memberDAO.listMembers(); request.setAttribute("membersList", membersList); forwardPage = "/member02/listmembers.jsp"; } //forwardPage에 지정한 요청명으로 다시 서블릿에 요청함 RequestDispatcher dispatcher = request.getRequestDispatcher(forwardPage); dispatcher.forward(request, response); } }
listmembers.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <c:set var="contextPath" value="${pageContext.request.contextPath }"/> <% request.setCharacterEncoding("utf-8"); %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Insert title here</title> <style type="text/css"> .cls1{ font-size: 40px; text-align: center; } .cls2{ font-size: 20px; text-align: center; } </style> <c:choose> <c:when test="${msg == 'modified' }"> <script type="text/javascript"> window.onload = function() { alert("회원 정보를 수정했습니다."); } </script> </c:when> <c:when test="${msg == 'deleted' }"> <script type="text/javascript"> window.onload = function() { alert("회원 정보를 삭제했습니다."); } </script> </c:when> </c:choose> </head> <body> <p class="cls1">회원정보</p> <table align="center" border="1"> <tr align="center" bgcolor="lightblue"> <td width="7%"><b>아이디</b></td> <td width="7%"><b>비밀번호</b></td> <td width="7%"><b>이름</b></td> <td width="7%"><b>이메일</b></td> <td width="7%"><b>가입일</b></td> <td width="7%"><b>수정</b></td> <td width="7%"><b>삭제</b></td> </tr> <c:choose> <c:when test="${empty membersList }"> <td colspan="5" align="center"> <b>등록된 회원이 없습니다.</b> </td> </c:when> <c:when test="${!empty membersList }"> <c:forEach var="mem" items="${membersList }"> <tr align="center"> <td>${mem.id }</td> <td>${mem.pwd }</td> <td>${mem.name }</td> <td>${mem.email }</td> <td>${mem.joinDate }</td> <td><a href="${contextPath }/member/modMemberForm.do?id=${mem.id }">수정</a></td> <td><a href="${contextPath }/member/delMember.do?id=${mem.id }">삭제</a></td> </tr> </c:forEach> </c:when> </c:choose> </table> <a href="${contextPath }/member/memberForm.do"><p class="cls2">회원 가입하기</p></a> </body> </html>
memberDAO.java package kr.co.ezenac.member02; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import kr.co.ezenac.member02.MemberVO; public class MemberDAO { private Connection conn; private PreparedStatement pstmt; private DataSource dataFactory; public MemberDAO() { try { Context ctx = new InitialContext(); Context envContext = (Context)ctx.lookup("java:/comp/env"); //JNDI에 접근하기 위해 기본경로를 지정 //톰캣 context.xml에 설정한 name 값인 jdbc/oracle을 이용해 톰캣이 미리 연결한 DataSource를 받아옴 dataFactory = (DataSource)envContext.lookup("jdbc/oracle"); } catch (NamingException e) { e.printStackTrace(); } } public List<MemberVO> listMembers() { List<MemberVO> membersList = new ArrayList<>(); try { conn = dataFactory.getConnection(); String query = "SELECT * FROM T_MEMBER ORDER BY JOINDATE DESC"; System.out.println(query); pstmt = conn.prepareStatement(query); ResultSet rs = pstmt.executeQuery(); while(rs.next()) { String id = rs.getString("id"); String pwd = rs.getString("pwd"); String name = rs.getString("name"); String email = rs.getString("email"); Date joinDate = rs.getDate("joinDate"); MemberVO memberVO = new MemberVO(id, pwd, name, email, joinDate); membersList.add(memberVO); } rs.close(); pstmt.close(); conn.close(); } catch(Exception e) { System.out.println("회원 조회 중 오류"); e.printStackTrace(); } return membersList; } public void addMember(MemberVO m) { try { conn = dataFactory.getConnection(); String id = m.getId(); String pwd = m.getPwd(); String name = m.getName(); String email = m.getEmail(); String query = "INSERT INTO T_MEMBER (ID, PWD, NAME, EMAIL) VALUES (?, ?, ?, ?)"; pstmt = conn.prepareStatement(query); pstmt.setString(1, id); pstmt.setString(2, pwd); pstmt.setString(3, name); pstmt.setString(4, email); pstmt.executeUpdate(); pstmt.close(); conn.close(); } catch(Exception e) { System.out.println("회원 가입 중 오류"); e.printStackTrace(); } } public MemberVO findMember(String _id) { MemberVO memInfo = null; try { conn = dataFactory.getConnection(); String query = "SELECT * FROM T_MEMBER WHERE ID=?"; pstmt = conn.prepareStatement(query); pstmt.setString(1, _id); System.out.println(query); ResultSet rs = pstmt.executeQuery(); rs.next(); String id = rs.getString("id"); String pwd = rs.getString("pwd"); String name = rs.getString("name"); String email = rs.getString("email"); Date joinDate = rs.getDate("joinDate"); memInfo = new MemberVO(id, pwd, name, email, joinDate); pstmt.close(); conn.close(); } catch (Exception e) { System.out.println("회원 정보 찾기 중 오류"); e.printStackTrace(); } return memInfo; } public void modMember(MemberVO memberVO) { String id = memberVO.getId(); String pwd = memberVO.getPwd(); String name = memberVO.getName(); String email = memberVO.getEmail(); try { conn = dataFactory.getConnection(); String query = "UPDATE T_MEMBER SET PWD=?, NAME=?, EMAIL=? WHERE ID=?"; System.out.println(query); pstmt = conn.prepareStatement(query); pstmt.setString(1, pwd); pstmt.setString(2, name); pstmt.setString(3, email); pstmt.setString(4, id); pstmt.executeUpdate(); pstmt.close(); conn.close(); } catch (Exception e) { System.out.println("회원 정보 수정 중 오류"); e.printStackTrace(); } } public void delMember(String id) { try { conn = dataFactory.getConnection(); String query = "DELETE FROM T_MEMBER WHERE ID=?"; System.out.println(query); pstmt = conn.prepareStatement(query); pstmt.setString(1, id); pstmt.executeUpdate(); pstmt.close(); conn.close(); } catch (Exception e) { System.out.println("회원 정보 삭제 중 오류"); e.printStackTrace(); } } }
memberVO.java package kr.co.ezenac.member02; import java.sql.Date; public class MemberVO { private String id; private String pwd; private String name; private String email; private Date joinDate; public MemberVO() { System.out.println("MemberVO 생성자 호출"); } public MemberVO(String id, String pwd, String name, String email) { this.id = id; this.pwd = pwd; this.name = name; this.email = email; } public MemberVO(String id, String pwd, String name, String email, Date joinDate) { super(); this.id = id; this.pwd = pwd; this.name = name; this.email = email; this.joinDate = joinDate; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Date getJoinDate() { return joinDate; } public void setJoinDate(Date joinDate) { this.joinDate = joinDate; } }
memberForm.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <c:set var="contextPath" value="${pageContext.request.contextPath }"/> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>회원 가입창</title> </head> <body> <form action="${contextPath }/member/addMember.do" method="post"> <h1 style="text-align: center;">회원 가입창</h1> <table align="center"> <tr> <td width="200"> <p align="right">아이디</p> </td> <td width="400"> <input type="text" name="id"> </td> </tr> <tr> <td width="200"> <p align="right">비밀번호</p> </td> <td width="400"> <input type="password" name="pwd"> </td> </tr> <tr> <td width="200"> <p align="right">이름</p> </td> <td width="400"> <input type="text" name="name"> </td> </tr> <tr> <td width="200"> <p align="right">이메일</p> </td> <td width="400"> <input type="text" name="email"> </td> </tr> <tr> <td width="200"> <p align="right"> </p> </td> <td width="400"> <input type="submit" value="가입하기"> <input type="reset" value="다시입력"> </td> </tr> </table> </form> </body> </html>
modMemberForm.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <c:set var="contextPath" value="${pageContext.request.contextPath }"/> <% request.setCharacterEncoding("utf-8"); %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Insert title here</title> </head> <body> <!-- 수정하기 클릭시 컨트롤러에 /member/modMember.do로 요청함 --> <form action="${contextPath }/member/modMember.do?id=${memInfo.id }" method="post"> <h1 style="text-align: center;">회원 정보 수정</h1> <table align="center"> <tr> <td width="200"> <p align="right">아이디</p> </td> <td width="400"> <!-- 조회한 회원 정보를 텍스트로 표시함 --> <input type="text" name="id" value="${memInfo.id }" disabled> </td> </tr> <tr> <td width="200"> <p align="right">비밀번호</p> </td> <td width="400"> <input type="password" name="pwd" value="${memInfo.pwd }"> </td> </tr> <tr> <td width="200"> <p align="right">이름</p> </td> <td width="400"> <input type="text" name="name" value="${memInfo.name }"> </td> </tr> <tr> <td width="200"> <p align="right">이메일</p> </td> <td width="400"> <input type="text" name="email" value="${memInfo.email }"> </td> </tr> <tr> <td width="200"> <p align="right">가입일</p> </td> <td width="400"> <input type="text" name="email" value="${memInfo.joinDate }" disabled> </td> </tr> <tr> <td width="200"> <p align="right"> </p> </td> <td width="400"> <input type="submit" value="수정하기"> <input type="reset" value="다시입력"> </td> </tr> </table> </form> </body> </html>
'개발자 수업 > JSP' 카테고리의 다른 글
28. WebSocket (0) 2022.02.03 27. Model2 방식 - 게시판 (0) 2021.12.22 25. Model2 방식 (0) 2021.12.21 24. jQuery Ajax (0) 2021.12.20 23. 파일 업로드 다운로드 (0) 2021.12.16