클라우드 융합 Full-stack 웹 개발자 양성과정/Servlet, JSP

Servlet/JSP - 마이페이지(비밀번호변경), 회원탈퇴, 공지사항

thesunset 2022. 11. 11. 16:32

1. 마이페이지(비밀번호 변경)

 

방법1) 비밀번호 페이지 새로 만든다. 

방법2) AJAX 사용

 

>> 모달 사용하기 

https://www.w3schools.com/bootstrap4/bootstrap_modal.asp

 

Bootstrap 4 Modals

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

에서 div요소 부분과 button의 data-toggle="modal" data-target="#updatePwdForm"속성추가

<button type="button" class="btn btn-sm btn-warning" data-toggle="modal" data-target="#updatePwdForm">비밀번호변경</button>

<!--비밀번호 변경 모달창 -->
<div class="modal" id="updatePwdForm">
    <div class="modal-dialog">
        <div class="modal-content">

    <!-- Modal Header -->
    <div class="modal-header">
      <h4 class="modal-title">비밀번호 변경</h4>
      <button type="button" class="close" data-dismiss="modal">&times;</button>
    </div>

    <!-- Modal body -->
    <div class="modal-body">
        <form action="<%= contextPath%>/updatePwd.me" method="post">
            <!-- 현재비밀번호, 변경할 비밀번호, 변경할비밀번호확인(재입력) -->
            <table>
                <tr>
                    <td>현재비밀번호</td>
                    <td><input type="password" required name="userPwd"></td>
                </tr>
                <tr>
                    <td>변경할 비밀번호</td>
                    <td><input type="password" required name="updatePwd"></td>
                </tr>
                <tr>
                    <td>변경할 비밀번호 재입력</td>
                    <td><input type="password" required name="checkPwd"></td>
                </tr>
            </table>

            <br>

            <button type="submit" class="btn btn-sm btn-primary" onclick="return validatePwd();">비밀번호 변경하기</button>

            <script>
                function validatePwd(){

                    if($('input[name=updatePwd]').val() != $('input[name=checkPwd]').val()){
                        alert('두 개의 비밀번호가 일치하지 않습니다.');
                        return false; //기본이벤트 지우는 방법
                    }else{
                        return true;
                    }
                };


            </script>

            <input type="hidden" name="userId" value="<%= userId %>" >
            <!-- 식별자로 사용할 아이디값 가져가기 , 사용자에게 보여지지 않기위해 타입을 hidden으로 지정! -->
        </form>
    </div>
    </div>
</div>
</div>

<com.kh.member.controller> MemberUpdateController

1) POST방식 => 인코딩

request.setCharacterEncoding("UTF-8");

2) request로부터 요청 시 전달한 값을 뽑기 

String userId = request.getParameter("userId");
String userPwd = request.getParameter("userPwd");
String updatePwd = request.getParameter("updatePwd");

식별자로 userId가 필요함 (where절에 사용하기 위해)
방법1. session만들어서 login에서 뽑아오기 
방법2. mypage.jsp에서 가져오기 => 선택

 

3) VO객체에 담기  => 담을 값이 너무 적을 땐 그대로 가져가기

4)Service단으로 전달 

Member updateMem = new MemberService().updatePwdMember(userId, userPwd, updatePwd);

5) 응답화면 지정

HttpSession session = request.getSession();

if(updateMem == null) {
    session.setAttribute("alertMsg", "비밀번호 변경 실패");
} else {
    session.setAttribute("alertMsg", "비밀번호 변경 성공");
    session.setAttribute("loginUser", updateMem); 
}

//성공/실패 모두 마이페이지를 보여줄 것
//localhost:8001/jsp/mypage.me

response.sendRedirect(request.getContextPath()+"/myPage.me");

 

<com.kh.member.model.service>Service

public Member updatePwdMember(String userId, String userPwd, String updatePwd) {

    Connection conn = JDBCTemplate.getConnection();

    //비밀번호 update관련 DAO메소드를 호출
    int result = new MemberDao().updatePwdMember(conn, userId, userPwd, updatePwd);

    //호출 결과에 따라서 성공이면 commit후에 새로 바뀐 회원정보를 다시 받아올 것
    Member updateMem = null;

    if(result > 0) {
        JDBCTemplate.commit(conn);
        //이미 만들어놔서 그대로 쓰면 됨
        updateMem = new MemberDao().selectMember(conn, userId);

    }else {
        JDBCTemplate.rollback(conn);
    }
    JDBCTemplate.close(conn);
    return updateMem;
}

<com.kh.member.model.dao>MemberDao

public int updatePwdMember(Connection conn, String userId, String userPwd, String updatePwd) {

    //UPDATE문 => 처리된 행의 개수 
    int result=0;
    PreparedStatement pstmt = null;
    String sql = prop.getProperty("updatePwdMember");

    try {
        pstmt = conn.prepareStatement(sql);
        pstmt.setString(1, updatePwd);
        pstmt.setString(2, userId);
        pstmt.setString(3, userPwd);

        result = pstmt.executeUpdate();

    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        JDBCTemplate.close(pstmt);
    }
    return result;
}

2. 회원탈퇴

myPage.jsp

<button type="button" class="btn btn-sm btn-danger" data-toggle="modal" data-target="#deleteForm">탈퇴</button>

<!--회원탈퇴 모달창 -->
<div class="modal" id="deleteForm">
    <div class="modal-dialog">
        <div class="modal-content">

    <!-- Modal Header -->
    <div class="modal-header">
      <h4 class="modal-title">회원탈퇴</h4>
      <button type="button" class="close" data-dismiss="modal">&times;</button>
    </div>

    <!-- Modal body -->
    <div class="modal-body">
        <form action="<%= contextPath%>/deleteMem.me" method="post">
            <table>
                <tr>
                    <td>비밀번호</td>
                    <td><input type="password" required name="userPwd"></td>
                </tr>
            </table>

            <br>

            <button type="submit" class="btn btn-sm btn-primary">탈퇴하기</button>

<com.kh.member.controller>MemberDeleteController

* 회원의 탈퇴 == 수정을 위해서는 식별값이 필요 

아이디를 가져오는 방법에는 2가지 방법이 있다. 

방법1. input type = "hidden"으로 애초에 숨겨서 전달하기
방법2. session 영역에 담겨 있는 회원 객체로부터 뽑아온다. 

request.setCharacterEncoding("UTF-8");

HttpSession session = request.getSession();

//방법2.
String userId = ((Member)session.getAttribute("loginUser")).getUserId();
String userPwd = request.getParameter("userPwd");

int result = new MemberService().deleteMem(userId, userPwd);


if(result > 0) {
    session.setAttribute("alertMsg", "탈퇴처리가 완료되었습니다.");
    //1) session.invalidate();
    //2) session.removeAttribute();
    session.removeAttribute("loginUser"); //2)
    response.sendRedirect(request.getContextPath());

}else {
    request.setAttribute("errorMsg", "회원탈퇴에 실패했습니다.");
    request.getRequestDispatcher("/views/common/errorPage");

1) session.invalidate(); => session을 만료 
2) session.removeAttribute();

<com.kh.member.model.service>Service

public int deleteMem(String userId, String userPwd) {

    Connection conn = JDBCTemplate.getConnection();

    int result = new MemberDao().deleteMem(conn, userId, userPwd);

    if(result > 0) {
        JDBCTemplate.commit(conn);
    }else {
        JDBCTemplate.rollback(conn);
    }

    JDBCTemplate.close(conn);

    return result;
}

<com.kh.member.model.dao>MemberDao

public int deleteMem(Connection conn, String userId, String userPwd) {

    int result = 0; 
    PreparedStatement pstmt = null;
    String sql = prop.getProperty("deleteMem");

    try {
        pstmt = conn.prepareStatement(sql);
        pstmt.setString(1, userId);
        pstmt.setString(2, userPwd);

        result = pstmt.executeUpdate();

    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        JDBCTemplate.close(pstmt);
    }

    return result;
}

3. 공지사항(게시판)

<com.kh.notice.vo>Notice

package com.kh.notice.model.vo;

import java.sql.Date;

public class Notice {

	private int noticeNo;
	private String noticeTitle;
	private String noticeContent;
	private String noticeWriter;
	private int count;
	private Date createDate;
	private String status;
	
	public Notice() {
		super();
	}

	public Notice(int noticeNo, String noticeTitle, String noticeContent, String noticeWriter, int count, Date createDate,
			String status) {
		super();
		this.noticeNo = noticeNo;
		this.noticeTitle = noticeTitle;
		this.noticeContent = noticeContent;
		this.noticeWriter = noticeWriter;
		this.count = count;
		this.createDate = createDate;
		this.status = status;
	}

	public int getNoticeNo() {
		return noticeNo;
	}

	public void setNoticeNo(int noticeNo) {
		this.noticeNo = noticeNo;
	}

	public String getNoticeTitle() {
		return noticeTitle;
	}

	public void setNoticeTitle(String noticeTitle) {
		this.noticeTitle = noticeTitle;
	}

	public String getNoticeContent() {
		return noticeContent;
	}

	public void setNoticeContent(String noticeContent) {
		this.noticeContent = noticeContent;
	}

	public String getNoticeWriter() {
		return noticeWriter;
	}

	public void setNoticeWriter(String noticeWriter) {
		this.noticeWriter = noticeWriter;
	}

	public int getCount() {
		return count;
	}

	public void setCount(int count) {
		this.count = count;
	}

	public Date getCreateDate() {
		return createDate;
	}

	public void setCreateDate(Date createDate) {
		this.createDate = createDate;
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	@Override
	public String toString() {
		return "Notice [noticeNo=" + noticeNo + ", noticeTitle=" + noticeTitle + ", noticeContent=" + noticeContent
				+ ", noticeWriter=" + noticeWriter + ", count=" + count + ", createDate=" + createDate + ", status="
				+ status + "]";
	}
}

myPage.jsp

<div class="menu"><a href="<%= contextPath %>/list.no">공지사항</a></div>

<com.kh.notice.controller>NoticeListController

1) 인코딩 => 전달받은 값이 없음
2) 값뽑기 => 전달받은 값이 없음
3) 가공 => 전달받은 값이 없음

화면을 띄우기 전에 NOTICE테이블에 들어있는 값을 뽑아서 응답페이지에 전달할 것을 생각하고 보내줘야 함
4) Service단으로 SELECT요청
공지사항 목록 => 가져올 행의 개수 : 최소 0개 ~ 최대는 알 수 없음 => ArrayList

ArrayList<Notice> list = new NoticeService().selectNoticeList();

request.setAttribute("list", list);

5) 포워딩

request.getRequestDispatcher("views/notice/noticeListView.jsp").forward(request, response);

<com.kh.notice.model.service>NoticeService

public ArrayList<Notice> selectNoticeList() {

    Connection conn = getConnection();

    ArrayList<Notice> list = new NoticeDao().selectNoticeList(conn);

    close(conn);

    return list;
}

<com.kh.notice.model.dao>NoticeDao

- properties파일과 input스트림을 이용해서 연결 & dao를 호출할 때마다 생성되도록 기본생성자 만들기

private Properties prop = new Properties();

//getPath()는 url을 문자열로 바꾸기 위함
public NoticeDao() {

    String file = NoticeDao.class.getResource("/sql/notice/notice-mapper.xml").getPath();
    try {
        prop.loadFromXML(new FileInputStream(file));
    } catch (IOException e) {
        e.printStackTrace();
    }
}
public ArrayList<Notice> selectNoticeList(Connection conn) {

    ArrayList<Notice> list = new ArrayList();
    PreparedStatement pstmt = null;
    ResultSet rset = null;

    String sql = prop.getProperty("selectNoticeList");

    try {
        pstmt = conn.prepareStatement(sql);

        rset = pstmt.executeQuery();

            while(rset.next()){
                Notice n = new Notice();

                n.setNoticeNo(rset.getInt("NOTICE_NO"));
                n.setNoticeTitle(rset.getString("NOTICE_TITLE"));
                n.setNoticeWriter(rset.getString("USER_ID")); //필드값을 그래서 String으로 자료형을 줘야 함
                n.setCount(rset.getInt("COUNT"));
                n.setCreateDate(rset.getDate("CREATE_DATE"));

                list.add(n);
            }


    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        close(rset);
        close(pstmt);
    }
    return list;
}