본문 바로가기

웹 개발 한걸음

[Servlet] 회원가입 구현하기

** 이전에 JSP로 만들었던 코드를 이용해 이를 서블릿으로 구현해보았다. 

서블릿에서는 코드가 조금 변경되었다.

 

[JSP] 6강 - 회원가입 기능 구현

본 포스팅은 정보 제공용이 아닌 유튜브 동빈나님의 JSP 게시판 만들기 강좌 6강을 바탕으로 보고 배운 것을 직접 정리해본 포스트 입니다. 회원가입 기능 역시 로그인 기능과 크게 다르지 않아

egu99.tistory.com

 


** 간략 프로세스

-> 회원가입 버튼

-> JoinControl의 doGet에 의해 join.jsp로.

-> (이 때 로그인 되어있는 상태라면 join.jsp 이동 전에 제지 당함)

-> 가입 양식 작성.

-> 작성한 양식 form이 post방식으로 joinControl의 getPost로.

-> 넘겨받은 양식을 인자로 UserDAO의 join메서드를 호출.

-> 가입

 


 

** JoinControl - doGet()

@WebServlet("/join")
public class JoinControl extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		HttpSession session = request.getSession();
		
		if(session.getAttribute("userID")!=null) {
			PrintWriter script = response.getWriter();
			script.println("<script>");
			script.println("alert('이미 로그인이 되어 있습니다.')");
			script.println("location.href = 'main'");
			script.println("</script>");
		} else {
			request.getRequestDispatcher("/WEB-INF/join.jsp").forward(request, response);
		}
	}

}

 

  • 회원가입 버튼을 누르면 이곳으로 와진다.
  • 단, 지금 로그인 중이라면 회원가입 할 수 없도록 메인으로 보내버린다.

 


** join.jsp

<!-- 회원가입 컨테이너 -->
	<div class="container">
		<div class="col-lg-4">
			<!-- 점보트론 -->
			<div class="jumbotron" style="padding-top:20px;">
				<!-- form의 데이터 전송 방식과 어디로 전송할지 -->
				<form method="post" action="join">
					<h3 style="text-align: center;">회원가입 화면</h3>
					<div class="form-group">
						<input type="text" class="form-control" placeholder="아이디" name="userID" maxlength="20">
					</div>
					<div class="form-group">
						<input type="password" class="form-control" placeholder="비밀번호" name="userPassword" maxlength="20">
					</div>
					<div  class="form-group">
						<input type="text" class="form-control" placeholder="이름" name="userName" maxlength="20">
					</div>
					<div  class="form-group" style="text-align: center;">
						<div class="btn-group" data-toggle="buttons">
							<label class="btn btn-primary active">
								<input type="radio" name="userGender" autocomplete="off" value="남자" checked> 남자
							</label>
							<label class="btn btn-primary">
								<input type="radio" name="userGender" autocomplete="off" value="여자">여자
							</label>
						</div>
					</div>
					<div  class="form-group">
						<input type="email" class="form-control" placeholder="이메일" name="userEmail" maxlength="20">
					</div>
					<input type="submit" class="btn btn-primary form-control" value="회원가입">
				</form>
			</div>
		</div>
	</div>

 

  • 회원가입 form이다. 
  • 가입 버튼을 누르면 작성한 form의 양식들이 post방식으로 url맵핑이름이 join인 서블릿에 submit하게 된다.

 

 


 

** JoinControl - doPost()

@WebServlet("/join")
public class JoinControl extends HttpServlet {

	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String userID = request.getParameter("userID");
		String userPassword = request.getParameter("userPassword");
		String userName = request.getParameter("userName");
		String userGender = request.getParameter("userGender");
		String userEmail = request.getParameter("userEmail");
	
		if(userID == null || userPassword == null || userName== null || userGender == null || userEmail == null ){
			PrintWriter script = response.getWriter();
			script.println("<script>");
			script.println("alert('누락된 정보가 있습니다.')");
			script.println("history.back'");
			script.println("</script>");
		}else{
			User user = new User(userID, userPassword, userName, userGender, userEmail);
			UserDAO userDAO = new UserDAO();
			int result = userDAO.join(user);
				
			if(result ==1){
				//세션 부여
				HttpSession session = request.getSession();
				session.setAttribute("userID", user.getUserID());
				PrintWriter script = response.getWriter();
				script.println("<script>");
				script.println("alert('회원가입 성공!.')");
				script.println("location.href = 'main'");
				script.println("</script>");
			}else if (result == -1){
				PrintWriter script = response.getWriter();
				script.println("<script>");
				script.println("alert('데이터베이스 오류.')");
				script.println("histroy.back()");
				script.println("</script>");
				
			}
		}
}
}

 

  • 넘겨받은 가입 양식을 전부 받는다.
  • 여기서 사실 컨트롤로 넘어오기 전에 VIEW 단에서 자바스크립트로 누락을 체크해야한다.
  • 당장은 서블릿으로 바꾸는 과정이므로 나중에 바꿔준다.
  • JSP 프로젝트 당시에는 자바빈으로 VO를 만들었지만 더이상 이를 쓰지 않으므로 VO인 User에서 Constructor Using Field로 생성자를 만들어준다. (당연히 기본생성자도 만들어준다.)
  • 이를 인자로 UserDAO의 Join()을 호출한다.

 


 

** User.java

package com.egu.web.entity;

public class User {

	private String userID;
	private String userPassword;
	private String userName;
	private String userGender;
	private String userEmail;
	public String getUserID() {
		return userID;
	}
	public void setUserID(String userID) {
		this.userID = userID;
	}
	public String getUserPassword() {
		return userPassword;
	}
	public void setUserPassword(String userPassword) {
		this.userPassword = userPassword;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getUserGender() {
		return userGender;
	}
	public void setUserGender(String userGender) {
		this.userGender = userGender;
	}
	public String getUserEmail() {
		return userEmail;
	}
	public void setUserEmail(String userEmail) {
		this.userEmail = userEmail;
	}
	public User(String userID, String userPassword, String userName, String userGender, String userEmail) {
		super();
		this.userID = userID;
		this.userPassword = userPassword;
		this.userName = userName;
		this.userGender = userGender;
		this.userEmail = userEmail;
	}
	public User() {
	
	}
	
}
  • 생성자를 만들어주었다.

 

 


** UserDAO.join()

public class UserDAO {

	//데이터베이스를 접근하게 해주는 객체.
	private Connection conn;
	//쿼리문을 미리 준비해두는 객체.
	private PreparedStatement pst;
	//쿼리를 실행시키고 결과값을 내는 객체.
	private ResultSet rs;
    
	public int join(User user) {
		
		String sql = "INSERT INTO USER VALUES(?,?,?,?,?)";
		try {
			
			pst = conn.prepareStatement(sql);
			pst.setString(1, user.getUserID());
			pst.setString(2, user.getUserPassword());
			pst.setString(3, user.getUserName());
			pst.setString(4, user.getUserGender());
			pst.setString(5, user.getUserEmail());
			
			return pst.executeUpdate();
				
		} catch (SQLException e) {		
			e.printStackTrace();
		}
		return -1;	
	}

}

 

  • JDBC로 DB에 접근하여 회원 가입하는 코드.