SMALL
안녕하세요, 코린이의 코딩 학습기 채니 입니다.
개인 포스팅용으로 내용에 오류 및 잘못된 정보가 있을 수 있습니다.
회원가입
header.jsp
<input type="button" value="회원가입"
onclick="location.href='<%= request.getContextPath()%>/member/memberEnroll';">
Controller
MemberEnrollServlet
@WebServlet("/member/memberEnroll")
public class MemberEnrollServlet 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/memberEnroll.jsp").forward(request, response);
}
/**
* db insert 요청
*
* insert into member values (?, ?, ?, default, ?, ?, ?, ?, ?, default, default)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1. 인코딩 처리
request.setCharacterEncoding("utf-8");
// 2. 사용자입력값 처리
String memberId = request.getParameter("memberId");
String password = request.getParameter("password");
String memberName = request.getParameter("memberName");
String _birthday = request.getParameter("birthday");
String _gender = request.getParameter("gender");
String email = request.getParameter("email");
String phone = request.getParameter("phone");
String[] hobbies = request.getParameterValues("hobby");
Gender gender = _gender != null ? Gender.valueOf(_gender) : null;
String hobby = hobbies != null ? String.join(",", hobbies) : null;
Date birthday = (_birthday != null && !"".equals(_birthday)) ? Date.valueOf(_birthday) : null;
Member member = new Member(memberId, password, memberName, null, gender, birthday, email, phone, hobby, 0, null);
System.out.println("member@MemberEnrollServlet = " + member);
// 3. 업무로직 : db insert
int result = memberService.insertMember(member);
System.out.println("result@MemberEnrollServlet = " + result);
// 4. 응답처리 : redirect
request.getSession().setAttribute("msg", "회원가입이 정상적으로 처리 되었습니다.");
response.sendRedirect(request.getContextPath() + "/");
}
}
URL을 아끼기 위해서 회원가입 버튼을 누를 때는 GET방식으로 서버에 요청을 보낸 후, jsp에게 위임을 하였고
회원가입 창에서 폼을 제출하면 POST방식으로 서버에 요청을 보내 회원가입처리를 하도록 하였습니다.
MemberEnroll.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/views/common/header.jsp" %>
<section id=enroll-container>
<h2>회원 가입 정보 입력</h2>
<form name="memberEnrollFrm" action="" method="POST">
<table>
<tr>
<th>아이디<sup>*</sup></th>
<td>
<input type="text" placeholder="4글자이상" name="memberId" id="_memberId" required>
</td>
</tr>
<tr>
<th>패스워드<sup>*</sup></th>
<td>
<input type="password" name="password" id="_password" required><br>
</td>
</tr>
<tr>
<th>패스워드확인<sup>*</sup></th>
<td>
<input type="password" id="passwordCheck" required><br>
</td>
</tr>
<tr>
<th>이름<sup>*</sup></th>
<td>
<input type="text" name="memberName" id="memberName" required><br>
</td>
</tr>
<tr>
<th>생년월일</th>
<td>
<input type="date" name="birthday" id="birthday" ><br />
</td>
</tr>
<tr>
<th>이메일</th>
<td>
<input type="email" placeholder="abc@xyz.com" name="email" id="email"><br>
</td>
</tr>
<tr>
<th>휴대폰<sup>*</sup></th>
<td>
<input type="tel" placeholder="(-없이)01012345678" name="phone" id="phone" maxlength="11" required><br>
</td>
</tr>
<tr>
<th>성별 </th>
<td>
<input type="radio" name="gender" id="gender0" value="M">
<label for="gender0">남</label>
<input type="radio" name="gender" id="gender1" value="F">
<label for="gender1">여</label>
</td>
</tr>
<tr>
<th>취미 </th>
<td>
<input type="checkbox" name="hobby" id="hobby0" value="운동"><label for="hobby0">운동</label>
<input type="checkbox" name="hobby" id="hobby1" value="등산"><label for="hobby1">등산</label>
<input type="checkbox" name="hobby" id="hobby2" value="독서"><label for="hobby2">독서</label><br />
<input type="checkbox" name="hobby" id="hobby3" value="게임"><label for="hobby3">게임</label>
<input type="checkbox" name="hobby" id="hobby4" value="여행"><label for="hobby4">여행</label><br />
</td>
</tr>
</table>
<input type="submit" value="가입" >
<input type="reset" value="취소">
</form>
</section>
<script>
/**
* 비밀번호 일치 여부 검사
*/
document.querySelector("#passwordCheck").onblur = (e) => {
const password = document.querySelector("#_password");
const passwordCheck = e.target;
if(password.value !== passwordCheck.value) {
alert("비밀번호가 일치하지 않습니다.");
password.select();
}
}
/**
* 폼 유효성 검사
*/
document.memberEnrollFrm.onsubmit = (e) => {
const memberId = document.querySelector("#_memberId");
if(!/^[a-zA-Z0-9]{4,}$/.test(memberId.value)) {
alert("아이디는 영문자/숫자 최소 4글자 이상이어야 합니다.");
memberId.select();
return false;
}
const password = document.querySelector("#_password");
if(!/^[a-zA-Z0-9!@#$%^&*()]{4,}$/.test(password.value)) {
alert("비밀번호는 영문자/숫자/!@#$%^&*()로 최소 4글자 이상이어야 합니다.");
password.select();
return false;
}
const passwordCheck = document.querySelector("#passwordCheck");
if(password.value !== passwordCheck.value) {
alert("비밀번호가 일치하지 않습니다.");
password.select();
return false;
}
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>
<%@ include file="/WEB-INF/views/common/footer.jsp" %>
유효성 검사를 통해 올바르게 입력을 했을 때만 제출되도록 하였습니다.
Service
MemberService
/**
* DML 요청 - service
* 1. Connection 객체 생성
* 2. Dao 요청 & Connection 전달
* 3. 트랜잭션 처리 (정상처리 commit, 예외발생 rollback)
* 4. Connection 반환 (close)
*/
public int insertMember(Member member) {
Connection conn = getConnection();
int result = 0;
try {
result = memberDao.insertMember(conn, member);
commit(conn);
} catch(Exception e) {
rollback(conn);
} finally {
close(conn);
}
return result;
}
Dao
MemberDao
/**
* DML 요청 - DAO
* 1. PreparedStatement 객체 생성 (sql 전달) & 값 대입
* 2. 쿼리실행 executeUpdate - int 반환
* 4. preparedStatement 객체 반환
*/
public int insertMember(Connection conn, Member member) {
PreparedStatement pstmt = null;
int result = 0;
String sql = prop.getProperty("insertMember");
// insert into member values (?, ?, ?, default, ?, ?, ?, ?, ?, default, default) properties에 저장
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, member.getMemberId());
pstmt.setString(2, member.getPassword());
pstmt.setString(3, member.getMemberName());
pstmt.setString(4, member.getGender() != null ? member.getGender().name() : null);
pstmt.setDate(5, member.getBirthday());
pstmt.setString(6, member.getEmail());
pstmt.setString(7, member.getPhone());
pstmt.setString(8, member.getHobby());
result = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
close(pstmt);
}
return result;
}
입력한 신사임당에 대한 정보가 잘 저장된 것을 확인할 수 있습니다.
enum 타입을 set할 수 없기 때문에 해당하는 값을 문자열로 반환해주는 name() 메소드를 이용하여 setString해주었습니다.
(toString()도 가능!)
LIST
'Java > Servlet & JSP' 카테고리의 다른 글
JSP) 회원가입 아이디 중복 검사 (0) | 2022.06.25 |
---|---|
JSP) 예외 처리 (0) | 2022.06.24 |
JSP) 아이디 저장 체크 박스 설정/미설정, 쿠키의 종류 (0) | 2022.06.23 |
JSP) 데이터 저장 용도로 존재하는 객체, 서블릿 이벤트 리스너 (0) | 2022.06.22 |
JSP) 기본적인 session과 cookie의 흐름, session의 유효기간 (0) | 2022.06.22 |