SMALL
안녕하세요, 코린이의 코딩 학습기 채니 입니다.
개인 포스팅용으로 내용에 오류 및 잘못된 정보가 있을 수 있습니다.
@실습문제 - 회원 정보 수정
- 세션정보도 함께 갱신
memberView.jsp
<%@page import="java.util.Arrays"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/views/common/header.jsp" %>
<%
// header.jsp에 loginMember를 선언해뒀으므로, 바로 호출 가능!
String memberId = loginMember.getMemberId();
String memberName = loginMember.getMemberName();
String birthday = loginMember.getBirthday() != null ? loginMember.getBirthday().toString() : "";
String email = loginMember.getEmail() != null ? loginMember.getEmail() : "";
String phone = loginMember.getPhone();
int point = loginMember.getPoint();
String gender = loginMember.getGender() != null ? loginMember.getGender().name() : "";
String hobby = loginMember.getHobby();
List<String> hobbyList = null;
if(hobby != null) {
String[] hobbyArr = hobby.split(",");
hobbyList = Arrays.asList(hobbyArr); // String[] -> List<String>
}
%>
<section id=enroll-container>
<h2>회원 정보</h2>
<form name="memberUpdateFrm" method="post" action="">
<table>
<tr>
<th>아이디<sup>*</sup></th>
<td>
<input type="text" name="memberId" id="memberId" value="<%= memberId %>" readonly>
</td>
</tr>
<tr>
<th>이름<sup>*</sup></th>
<td>
<input type="text" name="memberName" id="memberName" value="<%= memberName %>" required><br>
</td>
</tr>
<tr>
<th>생년월일</th>
<td>
<input type="date" name="birthday" id="birthday" value="<%= birthday %>"><br>
</td>
</tr>
<tr>
<th>이메일</th>
<td>
<input type="email" placeholder="abc@xyz.com" name="email" id="email" value="<%= email %>"><br>
</td>
</tr>
<tr>
<th>휴대폰<sup>*</sup></th>
<td>
<input type="tel" placeholder="(-없이)01012345678" name="phone" id="phone" maxlength="11" value="<%= phone %>" required><br>
</td>
</tr>
<tr>
<th>포인트</th>
<td>
<input type="text" placeholder="" name="point" id="point" value="<%= point %>" readonly><br>
</td>
</tr>
<tr>
<th>성별 </th>
<td>
<input type="radio" name="gender" id="gender0" value="M" <%= "M".equals(gender) ? "checked" : "" %>>
<label for="gender0">남</label>
<input type="radio" name="gender" id="gender1" value="F" <%= "F".equals(gender) ? "checked" : "" %>>
<label for="gender1">여</label>
</td>
</tr>
<tr>
<th>취미 </th>
<td>
<input type="checkbox" name="hobby" id="hobby0" value="운동" <%= hobbyCheck(hobbyList, "운동") %>><label for="hobby0">운동</label>
<input type="checkbox" name="hobby" id="hobby1" value="등산" <%= hobbyCheck(hobbyList, "등산") %>><label for="hobby1">등산</label>
<input type="checkbox" name="hobby" id="hobby2" value="독서" <%= hobbyCheck(hobbyList, "독서") %>><label for="hobby2">독서</label><br />
<input type="checkbox" name="hobby" id="hobby3" value="게임" <%= hobbyCheck(hobbyList, "게임") %>><label for="hobby3">게임</label>
<input type="checkbox" name="hobby" id="hobby4" value="여행" <%= hobbyCheck(hobbyList, "여행") %>><label for="hobby4">여행</label><br />
</td>
</tr>
</table>
<input type="submit" value="정보수정"/>
<input type="button" onclick="deleteMember();" value="탈퇴"/>
</form>
</section>
<script>
document.memberUpdateFrm.onsubmit = () => {
const memberName = document.querySelector("#memberName");
if(!/^[가-힣]{2,}$/.test(memberName.value)) {
alert("한글 2글자 이상을 입력해주세요.");
memberName.select();
return false;
}
const phone = document.querySelector("#phone");
if(!/^010[0-9]{8}$/.test(phone.value)) {
alert("유효한 전화번호를 입력해주세요.");
phone.select();
return false;
}
};
</script>
<%!
/**
* compile시 메소드로 선언처리됨.
* 선언위치는 어디든 상관없다.
*/
public String hobbyCheck(List<String> hobbyList, String hobby) {
return hobbyList != null && hobbyList.contains(hobby) ? "checked" : "";
}
%>
<%@ include file="/WEB-INF/views/common/footer.jsp" %>
Controller
memberViewServlet
@WebServlet("/member/memberView")
public class MemberViewServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private MemberService memberService = new MemberService();
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF/views/member/memberView.jsp").forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
String memberId = request.getParameter("memberId");
String memberName = request.getParameter("memberName");
String _birthday = request.getParameter("birthday");
String email = request.getParameter("email");
String phone = request.getParameter("phone");
String _gender = request.getParameter("gender");
String[] hobbies = request.getParameterValues("hobby");
Date birthday = _birthday != null && !"".equals(_birthday) ? Date.valueOf(_birthday) : null;
Gender gender = _gender != null ? Gender.valueOf(_gender) : null;
String hobby = hobbies != null ? String.join(",", hobbies) : null;
Member member = new Member(memberId, null, memberName, null, gender, birthday, email, phone, hobby, 0, null);
int result = memberService.updateMember(member);
HttpSession session = request.getSession();
if(result > 0) {
session.setAttribute("loginMember", memberService.findById(memberId));
}
session.setAttribute("msg", "회원 정보 수정이 완료되었습니다.");
response.sendRedirect(request.getContextPath() + "/member/memberView");
} catch(Exception e) {
e.printStackTrace();
throw e;
}
}
}
Service
memberService
// 회원 정보 수정
public int updateMember(Member member) {
Connection conn = getConnection();
int result = 0;
try {
result = memberDao.updateMember(conn, member);
commit(conn);
} catch(Exception e) {
rollback(conn);
throw e;
} finally {
close(conn);
}
return result;
}
Dao
memberDao
// 회원 정보 수정
// update member set member_name = ?, birthday = ?, email = ?, phone = ?, gender = ?, hobby = ? where member_id = ?
public int updateMember(Connection conn, Member member) {
PreparedStatement pstmt = null;
int result = 0;
String sql = prop.getProperty("updateMember");
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, member.getMemberName());
pstmt.setDate(2, member.getBirthday());
pstmt.setString(3, member.getEmail());
pstmt.setString(4, member.getPhone());
pstmt.setString(5, member.getGender() != null ? member.getGender().name() : null);
pstmt.setString(6, member.getHobby());
pstmt.setString(7, member.getMemberId());
result = pstmt.executeUpdate();
} catch (SQLException e) {
throw new MemberException("회원정보 수정 오류!", e);
} finally {
close(pstmt);
}
return result;
}
session도 함께 수정하여 [memberName]이 변경한 이름으로 세팅 및 수정된 정보가 확인 되도록 하였습니다.
LIST
'Java > └ [Servlet & JSP] Practice' 카테고리의 다른 글
[실습문제] 첨부파일 없는 게시글 수정 (0) | 2022.07.05 |
---|---|
[실습문제] 게시글 등록 (0) | 2022.07.02 |
[실습문제] 내 정보 보기 (0) | 2022.06.25 |