[Servlet&JSP] Chap 6-3. JSP 이용 회원 CRUD 구현하기(회원가입)

김승현·2021년 11월 27일
0
post-custom-banner

회원 가입 로직

  1. 사용자가 index.jsp 페이지에서 회원가입 버튼 클릭
    -> memberJoinUs.html
  2. memberJoinUs.html에서 로그인 정보 입력 폼 제공
  3. 사용자자가 정보 입력, 가입하기 버튼 클릭
    -> memberJoin.jsp
  4. memberJoin.jsp에서 회원 가입 처리(DB 등록)을 위한 비즈니스 로직 처리
    -> Service -> DAO -> DB
  5. memberJoin.jsp에서 비즈니스 로직 처리 후 리턴한 값을 통하여 가입 성공 여부를 출력
    • 성공 : memberJoinSuccess.jsp 이동 (pageContext.forward() 메소드 이용)
    • 실패 : memberJoinFail.jsp 이동 (pageContext.forward() 메소드 이용)




index.jsp

<%@page import="kr.or.test.member.model.vo.Member"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

	<h1>혀니의 메인 페이지</h1>
	
	
	<%
		Member m = (Member)session.getAttribute("member");
		
		//session에서 'memeber'라는 key를 가지고, 데이터를 꺼냈을때
		// 2가지 경우가 있다.
		// 1. Member 객체가 정상적으로 있는 경우(로그인을 한 사람인 경우)
		// 2. null 인 경우(로그인을 실행하였거나 혹은 로그인을 하지 않은 경우)
	%>
	
	<%if(m!=null){ %>
		[<%=m.getUserName() %>]님 환영합니다 <a href="/views/member/logout.jsp">로그아웃</a> <br>
	<%} else{%>
		<form action="/views/member/memberLogin.jsp" method="post">
		<fieldset style="width:300px;">
			<legend>로그인</legend>
			ID : <input type="text" name="userId" placeholder="ID를 입력하세요"><br>
			PW : <input type="password" name="userPwd" placeholder="패스워드를 입력하세요"><br>
			<input type="submit" value="로그인">
			</fieldset>
		</form>	
		<a href="/views/member/memberJoinUs.html">회원 가입</a>
	<%} %>

</body>
</html>



memberJoinUs.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>

<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>


<style>
	fieldset{
		width:300px;
		height:500px;
		margin:0 auto;
	}
	legend{
		text-align:center;
	}
	
</style>

</head>
<body>
	<form action="/views/member/memeberJoin.jsp" method="post">
		<fieldset>
			<legend>회원 가입</legend>
			회원 ID : <input type="text" name="userId" placeholder="ID를 입력하세요"><br>
			비밀 번호 : <input type="password" name="userPwd" placeholder="PW를 입력하세요"><br>
			비밀 번호(re) : <input type="password" name="userPwd_re" placeholder="PW를 재입력하세요"><br>
			이름 : <input type="text" name="userName" placeholder="이름을 입력하세요"><br>
			나이 : <input type="text" name="age" size=3><br>
			이메일 : <input type="email" name="email" size=30 placeholder="@ 형식의 이메일을 입력하세요"><br>
			휴대폰 : <input type="text" name="phone" placeholder="폰번호를 입력하세요"><br>
			주소 : <input type="text" name="address" placeholder="주소를 입력하세요"><br>
			성별 : <input type="radio" name="gender" value="M" checked><input type="radio" name="gender" value="F"><br>
			취미 <br>
			<input type="checkbox" name="hobby" value="운동">운동 
			<input type="checkbox" name="hobby" value="등산">등산 
			<input type="checkbox" name="hobby" value="독서">독서<br> 
			<input type="checkbox" name="hobby" value="노래">노래 
			<input type="checkbox" name="hobby" value="댄스">댄스 
			<input type="checkbox" name="hobby" value="기타">기타 <br>
			<br><br>
			<input type="submit" value="가입하기" id="joinBtn"> <input type="reset" value="다시 입력하기"><br><br>
			<a href="/">메인 페이지로 돌아가기</a>
		</fieldset>
	
	</form>
	
	
	<script>
		$('#joinBtn').click(function(){
			// 간단한 유효성 검사
			var userPwd=$('input[name=userPwd]').val();
			var userPwd_re=$('input[name=userPwd_re]').val();
			
			if(userPwd!=userPwd_re){
				alert('비밀번호와 비밀번호 재입력 값이 같아야 합니다.');
				return false
			}
			
			return true;
		});
	
	</script>
	
</body>
</html>



memberJoin.jsp

<%@page import="kr.or.test.member.model.vo.Member"%>
<%@page import="kr.or.test.member.model.service.MemberServiceImpl"%>
<%@page import="kr.or.test.member.model.service.MemberService"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

	<%
		// 이전 회원가입 페이지에서 보내온 값 가져오기
		request.setCharacterEncoding("UTF-8");
		String userId = request.getParameter("userId");
		String userPwd = request.getParameter("userPwd");
		String userName = request.getParameter("userName");
		int age = Integer.parseInt(request.getParameter("age"));
		String email = request.getParameter("email");
		String phone = request.getParameter("phone");
		String address = request.getParameter("address");
		char gender = request.getParameter("gender").charAt(0);
		String[] hobbyValues = request.getParameterValues("hobby"); // 배열로 넘어오는 데이터 받기

		String hobby;
		if (hobbyValues == null) { // 사용자가 취미를 선택하지 않았다면
			hobby = "";
		} else { // 사용자가 취미를 선택했다면
			hobby = hobbyValues[0];
			for (int i = 1; i < hobbyValues.length; i++) {
				hobby += ", " + hobbyValues[i];
			}
		}
		
		
		// 중간 확인
		/* System.out.println(userId);
		System.out.println(userPwd);
		System.out.println(userName);
		System.out.println(age);
		System.out.println(phone);
		System.out.println(email);
		System.out.println(address);
		System.out.println(userId);
		System.out.println("취미 : " + hobby); */

		Member m = new Member(userId, userPwd, userName, age, email, phone, address, gender, hobby);
		
		MemberService mService = new MemberServiceImpl();
		boolean result = mService.insertMemeber(m);
		
		// forwarding 기법
		if(result){
			pageContext.forward("/views/member/memberJoinSuccess.jsp");
		}else{
			pageContext.forward("/views/member/memberJoinFail.jsp");
		}
	%>
	
	<%-- <%if(result){ %>
		<script>
			alert('회원 가입 성공');
			location.replace('/views/member/memberJoinSuccess.jsp');
		</script>
	<%}else{ %>
		<script>
			alert('회원 가입 실패');
			location.replace('/views/member/memberJoinFail.jsp');
		</script>
	<%} %> --%>
	
	
</body>
</html>



MemberService.java

package kr.or.test.member.model.service;

import kr.or.test.member.model.vo.Member;

public interface MemberService {
	
	public boolean insertMemeber(Member m);
}

MemberServiceImpl.java

package kr.or.test.member.model.service;

import java.sql.Connection;

import kr.or.test.common.JDBCTemplate;
import kr.or.test.member.model.dao.MemberDAO;
import kr.or.test.member.model.vo.Member;

public class MemberServiceImpl implements MemberService {

	private MemberDAO mDAO = new MemberDAO();

	@Override
	public boolean insertMemeber(Member m) {
		Connection conn = JDBCTemplate.getConnection();
		int result = mDAO.insertMember(m, conn);

		if (result > 0) {	// 가입 성공
			JDBCTemplate.commit(conn);
			JDBCTemplate.close(conn);
			return true; 
		} else {	// 가입 실패
			JDBCTemplate.rollback(conn);
			JDBCTemplate.close(conn);
			return false;
		}

	}

}



MemberDAO.java

package kr.or.test.member.model.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import kr.or.test.common.JDBCTemplate;
import kr.or.test.member.model.vo.Member;

public class MemberDAO {

	public int insertMember(Member m, Connection conn) {
		
		PreparedStatement pstmt = null;
		int result= 0;
		
		String sql= "INSERT INTO MEMBER VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?,SYSDATE,'N')";
		
		try {
			pstmt=conn.prepareStatement(sql);
			pstmt.setString(1, m.getUserId());
			pstmt.setString(2, m.getUserPwd());
			pstmt.setString(3, m.getUserName());
			pstmt.setInt(4, m.getAge());
			pstmt.setString(5, m.getEmail());
			pstmt.setString(6, m.getPhone());
			pstmt.setString(7, m.getAddress());
			pstmt.setString(8, String.valueOf(m.getGender()));	// char 타입 -> String 타입으로 전환
			pstmt.setString(9, m.getHobby());
			
			// 리턴 처리 행 수 , 못햇다면 0 리턴
			result = pstmt.executeUpdate();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			JDBCTemplate.close(pstmt);
		}
		
		return result;
		
		
	}

}



JDBCTemplate.java

package kr.or.test.common;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCTemplate {

	// getConnection
	public static Connection getConnection() {

		Connection conn = null;

		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");

			conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "jsp", "jsp");

			conn.setAutoCommit(false);

		} catch (ClassNotFoundException e) {

			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return conn;
	}

	// commit
	public static void commit(Connection conn) {
		try {
			conn.commit();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// rollback
	public static void rollback(Connection conn) {
		try {
			conn.rollback();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	

	// close(Statement)
	public static void close(Statement stmt) {
		try {
			stmt.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// close(ResultSet)
	public static void close(ResultSet rset) {
		try {
			rset.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// close(Connection)
	public static void close(Connection conn) {
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}



Member.java

package kr.or.test.member.model.vo;

import java.sql.Date;

public class Member {
	private String userId;
	private String userPwd;
	private String userName;
	private int age;
	private String email;
	private String phone;
	private String address;
	private char gender;
	private String hobby;
	private Date enrollDate;
	private char endYN;

	public Member() {
		super();
		// TODO Auto-generated constructor stub
	}

	public Member(String userId, String userPwd, String userName, int age, String email, String phone, String address,
			char gender, String hobby, Date enrollDate, char endYN) {
		super();
		this.userId = userId;
		this.userPwd = userPwd;
		this.userName = userName;
		this.age = age;
		this.email = email;
		this.phone = phone;
		this.address = address;
		this.gender = gender;
		this.hobby = hobby;
		this.enrollDate = enrollDate;
		this.endYN = endYN;
	}
	
	
	//  회원 가입시에 필요한 데이터만 저장하기 위한 생성자
	public Member(String userId, String userPwd, String userName, int age, String email, String phone, String address,
			char gender, String hobby) {
		super();
		this.userId = userId;
		this.userPwd = userPwd;
		this.userName = userName;
		this.age = age;
		this.email = email;
		this.phone = phone;
		this.address = address;
		this.gender = gender;
		this.hobby = hobby;
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public String getUserPwd() {
		return userPwd;
	}

	public void setUserPwd(String userPwd) {
		this.userPwd = userPwd;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public char getGender() {
		return gender;
	}

	public void setGender(char gender) {
		this.gender = gender;
	}

	public String getHobby() {
		return hobby;
	}

	public void setHobby(String hobby) {
		this.hobby = hobby;
	}

	public Date getEnrollDate() {
		return enrollDate;
	}

	public void setEnrollDate(Date enrollDate) {
		this.enrollDate = enrollDate;
	}

	public char getEndYN() {
		return endYN;
	}

	public void setEndYN(char endYN) {
		this.endYN = endYN;
	}

}



memberJoinSuccess.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	
	<h1>회원가입을 축하합니다. - 이제 우리 사이트의 정식회원이 되셨어요!! -</h1>
	<a href="/">메인페이지로 이동</a><br>
	
</body>
</html>



memberJoinFail.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>회원가입에 실패하였습니다. - 지속적인 문제 발생 시 관리자에게 문의해주세요 -</h1>
	<a href="/">메인페이지로 이동</a><br>
</body>
</html>
profile
개발자로 매일 한 걸음
post-custom-banner

0개의 댓글