오늘이라도
[Web] 27. 회원 관리 & 게시판 만들기 ② : 로그인, 회원가입 구현 본문
https://github.com/upcake/Class_Examples
교육 중에 작성한 예제들은 깃허브에 올려두고 있습니다.
gif 파일은 클릭해서 보는 것이 정확합니다.
- 회원 관리 & 게시판 만들기 ② : 로그인, 회원가입 구현 -
○ 작동 순서
* 로그인
index.html → memberLogin.me → web.xml → MemberFrontController
→ loginForm.jsp → memberLoginAction.me → web.xml → MemberFrontController
회원가입 X → 회원가입 페이지 전환(joinForm.jsp)
회원가입 O → isMember() → BoardList
* 회원가입
memberJoin.me → web.xml → MemberFrontController → joinForm.jsp
→ memberJoinAction.me → web.xml → MemberFrontController → MemberJoinAction.java
→ MemberDAO.java → MemberJoinAction.java → MemberFrontController → memberLogin.me
○ 작동 화면 및 코드
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Index</title>
<script type="text/javascript">
location.href = "memberLogin.me";
</script>
</head>
<body>
</body>
</html>
▲index.html
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>09.Member_Board</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<display-name>MemberFrontController</display-name>
<servlet-name>MemberFrontController</servlet-name>
<servlet-class>com.member.action.MemberFrontController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MemberFrontController</servlet-name>
<url-pattern>*.me</url-pattern>
</servlet-mapping>
<servlet>
<display-name>BoardFrontController</display-name>
<servlet-name>BoardFrontController</servlet-name>
<servlet-class>com.board.action.BoardFrontController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>BoardFrontController</servlet-name>
<url-pattern>*.bo</url-pattern>
</servlet-mapping>
</web-app>
▲web.xml
package com.member.action;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
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 com.commons.action.Action;
import com.commons.action.ActionForward;
@WebServlet("/MemberFrontController.me")
public class MemberFrontController extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String uri = request.getRequestURI();
String context = request.getContextPath();
String command = uri.substring(context.length());
//System.out.println(command); //콘솔 창에 /memberLogin.me 등이 출력된다.
Action action = null;
ActionForward forward = null;
if(command.equals("/memberLogin.me")) {
forward = new ActionForward();
forward.setPath("member/loginForm.jsp");
forward.setRedirect(false);
} else if(command.equals("/memberLoginAction.me")) {
action = new MemberLoginAction();
forward = action.execute(request, response);
} else if(command.equals("/memberJoin.me")) {
forward = new ActionForward();
forward.setPath("member/joinForm.jsp");
forward.setRedirect(false);
} else if(command.equals("/memberJoinAction.me")) {
action = new MemberJoinAction();
forward = action.execute(request, response);
} else if(command.equals("/memberLogout.me")) {
action = new MemberLogoutAction();
forward = action.execute(request, response);
}
if(forward != null) {
if(forward.isRedirect()) { //true : sendRedirect() 전환
response.sendRedirect(forward.getPath());
} else { //false : forward() 전환
RequestDispatcher rd = request.getRequestDispatcher(forward.getPath());
rd.forward(request, response);
}
}
}
}
▲MemberFrontController.java
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>loginForm JSP</title>
</head>
<body>
<div align="center">
<h3>[로그인 페이지].</h3>
<form action="memberLoginAction.me" method="post">
<table border="1">
<tr>
<th>아이디</th>
<td><input type="text" name="member_id" /></td>
</tr>
<tr>
<th>비밀번호</th>
<td><input type="password" name="member_pw" /></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="로그인" />
<input type="button" value="회원가입" onclick="location.href='memberJoin.me'"/>
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
▲loginForm.jsp
package com.member.action;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.commons.action.Action;
import com.commons.action.ActionForward;
import com.member.study.MemberDAO;
import com.member.study.MemberDTO;
public class MemberLoginAction implements Action {
@Override
public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
MemberDTO dto = new MemberDTO();
dto.setMember_id(request.getParameter("member_id"));
dto.setMember_pw(request.getParameter("member_pw"));
MemberDAO dao = new MemberDAO();
int result = dao.isMember(dto);
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
if(result == 0) {
out.println("<script>");
out.println("alert('비밀번호가 일치하지 않습니다!');");
out.println("location.href = 'memberLogin.me';");
out.println("</script>");
return null;
} else if(result == -1) {
out.println("<script>");
out.println("alert('아이디가 존재하지 않습니다!');");
out.println("location.href = 'memberLogin.me';");
out.println("</script>");
return null;
} else { //로그인 성공
HttpSession session = request.getSession();
session.setAttribute("id", dto.getMember_id()); //바인딩 객체
ActionForward forward = new ActionForward();
forward.setPath("boardList.bo");
forward.setRedirect(false);
return forward;
}
}
}
▲MemberLoginAction.java
package com.member.action;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.commons.action.Action;
import com.commons.action.ActionForward;
public class MemberLogoutAction implements Action {
@Override
public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
session.removeAttribute("id");
ActionForward forward = new ActionForward();
forward.setPath("memberLogin.me");
forward.setRedirect(true);
return forward;
}
}
▲MemberLogoutAction.java
package com.member.study;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class MemberDAO {
private Connection conn;
private PreparedStatement ps;
private ResultSet rs;
public Connection getConn() {
String url = "jdbc:oracle:thin:@127.0.0.1:1521:XE";
String user = "hanul";
String password = "0000";
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
e.printStackTrace();
System.out.println("getConn() Exception!!!");
}
return conn;
} //getConn()
//joinMember : 회원가입
public boolean joinMember(MemberDTO dto) {
//① 접속
conn = getConn();
//② SQL 문장 작성
String sql = "INSERT INTO boardMember VALUES (?, ?, ?, ?, ?, ?)";
int succ = 0;
//③ try-catch 블록 작성 후 PreapareStatement 설정
try {
ps = conn.prepareStatement(sql);
ps.setString(1, dto.getMember_id());
ps.setString(2, dto.getMember_pw());
ps.setString(3, dto.getMember_name());
ps.setInt(4, dto.getMember_age());
ps.setString(5, dto.getMember_gender());
ps.setString(6, dto.getMember_email());
succ = ps.executeUpdate();
if(succ != 0) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("joinMember() Exception!!!");
}
return false;
} //joinMember()
//isMember : 회원 여부
public int isMember(MemberDTO dto) {
conn = getConn();
String sql = "SELECT member_pw FROM boardMember WHERE member_id = ?";
int result = -1;
try {
ps = conn.prepareStatement(sql);
ps.setString(1, dto.getMember_id());
rs = ps.executeQuery();
if(rs.next()) { //아이디 존재
if(rs.getString("member_pw").equals(dto.getMember_pw())) {
result = 1; //비밀번호 일치
} else {
result = 0; //비밀번호 불일치
}
} else { //아이디가 존재하지 않는다
result = -1;
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("isMember() Exception!!!");
}
return result;
} //isMember()
} //class
▲MemberDAO.java
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>join Form JSP</title>
</head>
<body>
<div align="center">
<h3>[회원가입 페이지]</h3>
<form action="memberJoinAction.me" method="post">
<table border="1">
<tr>
<th>아이디</th>
<td><input type="text" name="member_id" required="required"/></td>
</tr>
<tr>
<th>비밀번호</th>
<td><input type="password" name="member_pw" required="required"/></td>
</tr>
<tr>
<th>이름</th>
<td><input type="text" name="member_name" required="required"/></td>
</tr>
<tr>
<th>나이</th>
<td><input type="number" name="member_age" required="required" min="0" /></td>
</tr>
<tr>
<th>성별</th>
<td>
<input type="radio" name="member_gender" value="남" checked="checked" />남자
<input type="radio" name="member_gender" value="여" />여자
</td>
</tr>
<tr>
<th>이메일 주소</th>
<td><input type="text" name="member_email" maxlength="30"/></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="회원가입"/>
<input type="reset" value="다시 작성"/>
<input type="button" value="로그인" onclick="location.href='memberLogin.me'"/>
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
▲joinForm.jsp
package com.member.action;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.commons.action.Action;
import com.commons.action.ActionForward;
import com.member.study.MemberDAO;
import com.member.study.MemberDTO;
public class MemberJoinAction implements Action{
@Override
public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
//String member_id = request.getParameter("member-id");
MemberDTO dto = new MemberDTO();
dto.setMember_id(request.getParameter("member_id"));
dto.setMember_pw(request.getParameter("member_pw"));
dto.setMember_name(request.getParameter("member_name"));
dto.setMember_age(Integer.parseInt(request.getParameter("member_age")));
dto.setMember_gender(request.getParameter("member_gender"));
dto.setMember_email(request.getParameter("member_email"));
MemberDAO dao = new MemberDAO();
boolean result = dao.joinMember(dto);
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
if(result == false) {
out.println("<script>alert('회원가입 실패!')</script>");
return null;
} else {
ActionForward forward = new ActionForward();
forward.setPath("memberLogin.me");
forward.setRedirect(true);
return forward;
}
}
}
▲MemberJoinAction.java
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
String id = (String) session.getAttribute("id"); //JSP는 session이 내장 객체라 바로 사용 가능하다.
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>board list JSP</title>
</head>
<body>
<div align="center">
<h3>[자유 게시판]</h3>
<table>
<tr align="right">
<td>
<%if(id != null && id.equals("admin")) { %>
<input type="button" value="회원 관리" onclick="location.href='memberListAction.me'" />
<%} %>
<input type="button" value="로그아웃" onclick="location.href='memberLogout.me'"/>
<input type="button" value="글쓰기" onclick="location.href='boardWrite.bo'" />
</td>
</tr>
</table>
</div>
</body>
</html>
▲board_list.jsp
'취업성공패키지 SW 개발자 교육 > Web' 카테고리의 다른 글
[Web] 29. 회원 관리 & 게시판 만들기 ④ : 회원 정보 수정, 게시글 작성, 파일 업로드 (0) | 2020.06.18 |
---|---|
[Web] 28. 회원 관리 & 게시판 만들기 ③ : 회원 목록, 회원 정보 상세 보기, 회원 삭제 구현 (2) | 2020.06.17 |
[Web] 26. 회원 관리 & 게시판 만들기 ① : 웹 프로젝트 생성 및 페이지 작성 전 환경 준비 (3) | 2020.06.15 |
[Web] 25. ajax 통신을 이용한 json 출력 / xml 출력 / jsp 접근 (0) | 2020.06.11 |
[Web] 24. toggleClass, JSON을 jQuery로 읽기, ajax 통신 (0) | 2020.06.10 |