전까지는 로그인/로그아웃 기능을 작동되도록하였다.
이번에는 회원가입을 진행해보도록하겠습니다.
우선 화면단부터구성
이번 회원가입에는 주소API 사용예정입니다.
다른 카카오API도 있는데 사용하기 쉬우니깐 편한거쓰면될거같다.
https://www.poesis.org/postcodify/
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>회원가입</title>
<style>
.outer{
width:60%;
min-width : 650px;
background: rgb(248, 249, 250);
box-shadow: rgba(0, 0, 0, 0.06) 0px 0px 4px 0px;
margin:auto;
margin-top : 70px;
margin-bottom : 70px;
}
#joinForm {
width : 400px;
margin: auto;
padding: 10px;
}
#joinForm h1 {
text-align:center;
}
.input_area {
border: solid 1px #dadada;
padding : 10px 10px 14px 10px;
background : white;
}
.input_area input:not([type=checkbox]) {
width : 250px;
height : 30px;
border: 0px;
}
.btnArea {
text-align:center;
padding : 50px;
}
button {
width : 100px;
height : 35px;
border : 0px;
color:white;
background:#282A35;
margin : 5px;
}
</style>
</head>
<body>
<!-- index.jsp 생성 후 모든 페이지에 include할 menubar.jsp 생성 -->
<%@ include file="/WEB-INF/views/common/header.jsp" %>
<div class="outer">
<div id="joinInfoArea">
<form id="joinForm" action="<%= request.getContextPath() %>/memberJoin"
method="post" onsubmit="return validate();">
<h1>회원 가입</h1>
<h4>* 아이디</h4>
<span class="input_area"><input type="text" maxlength="13" name="userId" required></span>
<button id="idCheck" type="button">중복확인</button>
<h4>* 비밀번호</h4>
<span class="input_area"><input type="password" maxlength="15" name="userPwd" required></span>
<h4>* 비밀번호 확인</h4>
<span class="input_area"><input type="password" maxlength="15" name="userPwd2" required></span>
<label id="pwdResult"></label>
<h4>* 이름</h4>
<span class="input_area"><input type="text" maxlength="5" name="userName" required></span>
<h4>연락처</h4>
<span class="input_area"><input type="tel" maxlength="11" name="phone"
placeholder="(-없이)01012345678"></span>
<h4>이메일</h4>
<span class="input_area"><input type="email" name="email"></span>
<h4>우편번호</h4>
<span class="input_area"><input type="text" name="address" class="postcodify_postcode5"></span>
<button type="button" id="postcodify_search_button">검색</button>
<h4>도로명주소</h4>
<span class="input_area"><input type="text" name="address" class="postcodify_address"></span>
<h4>상세주소</h4>
<span class="input_area"><input type="text" name="address" class="postcodify_details"></span>
<h4>관심분야</h4>
<span class="input_area">
<input type="checkbox" id="sports" name="interest" value="운동">
<label for="sports">운동</label>
<input type="checkbox" id="climbing" name="interest" value="등산">
<label for="climbing">등산</label>
<input type="checkbox" id="fishing" name="interest" value="낚시">
<label for="fishing">낚시</label>
<input type="checkbox" id="cooking" name="interest" value="요리">
<label for="cooking">요리</label>
<input type="checkbox" id="game" name="interest" value="게임">
<label for="game">게임</label>
<input type="checkbox" id="etc" name="interest" value="기타">
<label for="etc">기타</label>
</span>
<div class="btnArea">
<button id="joinBtn">가입하기</button>
</div>
</form>
</div>
</div>
<!-- 주소 API 스크립트 -->
<!-- jQuery와 Postcodify를 로딩한다 -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="//d1p7wdleee1q2z.cloudfront.net/post/search.min.js"></script>
<!-- "검색" 단추를 누르면 팝업 레이어가 열리도록 설정한다 -->
<script> $(function() { $("#postcodify_search_button").postcodifyPopUp(); }); </script>
<script>
function validate(){
return true;
}
</script>
</body>
</html>
사용방법은 위의 페이지에서 적용예제보면 사용방법이있다.
우선 페이지에서 회원가입 버튼을 누르게되면
/memberJoin 으로 이동하게된다.
<%@page import="member.model.vo.Member"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
Member userLogin = (Member) request.getSession().getAttribute("userLogin");
// System.out.println(userLogin);
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link href="<%=request.getContextPath() %>/resources/css/menubar-style.css" rel="stylesheet">
<%if(session.getAttribute("msg") != null){ %>
<script>
alert('<%= (String) session.getAttribute("msg") %>');
</script>
<%
session.removeAttribute("msg");
} %>
</head>
<body>
<div class="wrapper">
<header id="header">
<!-- 로고 이미지를 클릭하면 첫 화면으로 -->
<a href="<%= request.getContextPath() %>">
<img class="logo" src="<%= request.getContextPath() %>/resources/images/logo.png" alt="JSP HOME">
</a>
<!-- 회원가입/로그인 -->
<div class="btnArea">
<%if(userLogin == null) {%>
<a href="<%= request.getContextPath() %>/memberJoin">회원가입</a>
<a href="<%= request.getContextPath() %>/login">로그인</a>
<%} else { %>
<a href="<%= request.getContextPath()%>/memberModify">정보수정</a>
<a href="<%= request.getContextPath()%>/logout">로그아웃</a>
<%} %>
</div>
</header>
<nav id="nav">
<ul>
<li><a href="<%= request.getContextPath() %>">HOME</a></li>
<li><a href="#">공지사항</a></li>
<li><a href="#">게시판</a></li>
<li><a href="#">사진게시판</a></li>
</ul>
</nav>
</div>
</body>
</html>
MemberJoinServlet.java
package member.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import member.model.vo.Member;
import member.service.MemberService;
@WebServlet("/memberJoin")
public class MemberJoinServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 회원가입 페이지로 이동
request.getRequestDispatcher("/WEB-INF/views/member/memberJoinForm.jsp").forward(request, response);
}
}
회원가입 페이지로 이동하게된다.
가입하기를 누르게되면
post방식으로 /memberJoin 으로 요청하게된다.
입력값을 반환받아 Member 객체에 저장후
Service -> DAO 로 값을 넘겨줘야한다.
package member.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import member.model.vo.Member;
import member.service.MemberService;
@WebServlet("/memberJoin")
public class MemberJoinServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 회원가입 페이지로 이동
request.getRequestDispatcher("/WEB-INF/views/member/memberJoinForm.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
// 입력값 받아오기
String userId = request.getParameter("userId");
String userPwd = request.getParameter("userPwd");
String userName = request.getParameter("userName");
String phone = request.getParameter("phone");
String email = request.getParameter("email");
String[] addressArr = request.getParameterValues("address");
String[] interestArr = request.getParameterValues("interest");
String address = "";
String interest = "";
// 주소값 하나의 문자열로 합치기
if(addressArr != null) {
address = String.join(",", addressArr);
}
// 취미 하나의 문자열로 합치기
if(interestArr != null) {
interest = String.join(",", interestArr);
}
// 받아온 값 Member 객체 저장
Member member = new Member(userId, userPwd, userName, phone, email, address, interest);
// System.out.println(member);
// 서비스로 값 전달
int result = new MemberService().memberJoin(member);
if(result > 0) {
request.getSession().setAttribute("msg", "회원가입에 성공하셨습니다. 로그인을 진행해주세요.");
response.sendRedirect(request.getContextPath());
}
}
}
MemberService
커넥션을 연결하고
insert의 작업은 int형으로 반환하기 때문에 result에 저장한다.
만약 저장에 성공했을시 commit하고
저장에 실패했다면 rollback 작업을 한다.
package member.service;
import static common.JDBCTemplate.*;
import java.sql.Connection;
import member.model.dao.MemberDAO;
import member.model.vo.Member;
public class MemberService {
// 1. 로그인
public Member loginMember(String id, String pwd) {
Connection conn = getConnection();
Member loginUser = new MemberDAO().loginMember(conn, id, pwd);
return loginUser;
}
// 회원가입
public int memberJoin(Member member) {
Connection conn = getConnection();
int result = new MemberDAO().memberJoin(conn, member);
if(result > 0) {
commit(conn);
}else {
rollback(conn);
}
close(conn);
return result;
}
}
MemberDAO
회원가입메소드를 확인하자
package member.model.dao;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import member.model.vo.Member;
import static common.JDBCTemplate.close;
public class MemberDAO {
Properties prop = new Properties();
public MemberDAO() {
String fileName = MemberDAO.class.getResource("/sql/member/member-query.xml").getPath();
try {
prop.loadFromXML(new FileInputStream(fileName));
} catch (IOException e) {
e.printStackTrace();
}
}
// 1. 로그인 기능
public Member loginMember(Connection conn, String id, String pwd) {
PreparedStatement pstmt = null;
ResultSet rs = null;
Member member = null;
String sql = prop.getProperty("loginMember");
// System.out.println(sql);
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, id);
pstmt.setString(2, pwd);
rs = pstmt.executeQuery();
if(rs.next()) {
member = new Member(
rs.getInt("USER_NO"),
rs.getString("USER_ID"),
rs.getString("USER_PWD"),
rs.getString("USER_NAME"),
rs.getString("PHONE"),
rs.getString("EMAIL"),
rs.getString("ADDRESS"),
rs.getString("INTEREST"),
rs.getDate("ENROLL_DATE"),
rs.getDate("MODIFY_DATE"),
rs.getString("STATUS")
);
// System.out.println(member);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
close(rs);
close(pstmt);
}
return member;
}
// 2. 회원가입
public int memberJoin(Connection conn, Member member) {
int result = 0;
PreparedStatement pstmt = null;
String sql = prop.getProperty("memberJoin");
// System.out.println(sql);
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, member.getUserId());
pstmt.setString(2, member.getUserPwd());
pstmt.setString(3, member.getUserName());
pstmt.setString(4, member.getPhone());
pstmt.setString(5, member.getEmail());
pstmt.setString(6, member.getAddress());
pstmt.setString(7, member.getInterest());
result = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
close(pstmt);
}
return result;
}
}
이런식으로 대부분의 로직이 활용되는것같다.
회원가입을 진행해보자.
의 정보를 입력하고 가입해보자
알림창 뜨면서 메인페이지로 이동되었다.
오류메세지 없나 확인해보고
데이터베이스 확인해보자.
방금 입력한 정보가 저장되어있는것을 확인할수 있다.
생각보다 간단해보이지만 ..중간중간 오류가좀발생하였다..
재미있습니다 ..
'프로그래밍 > JSP' 카테고리의 다른 글
JSP - EL/JSTL (0) | 2021.08.27 |
---|---|
JSP - 미니 프로젝트(5. 정보수정) (0) | 2021.08.23 |
JSP - 미니 프로젝트(3. 로그아웃) (0) | 2021.08.23 |
JSP - 미니 프로젝트(2. 로그인) (0) | 2021.08.23 |
JSP - 미니 프로젝트(1.메인페이지) (1) | 2021.08.23 |