[Servlet] 회원 가입, 로그인 페이지
by 무작정 개발반응형
2022.02.22(42일 차)
로그인 기능은 무조건 Session을 써야 한다.
여러 개의 데이터를 넣을 때는 클래스에 넣어서 Session에 올리면 된다.
가상 주소 : join
실제주소 : member
오늘의 수업 내용
오늘은 로그인 & 회원가입 페이지를 만들 예정입니다.
1. DB 생성하기 - (MEMBER)
userId를 Primary Key로 정해서 위의 방법대로 member 테이블을 생성합니다.
2. web.xml 등록
<!-- Servlet 회원가입 -->
<servlet>
<servlet-name>memberServlet</servlet-name>
<servlet-class>com.join.MemberServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>memberServlet</servlet-name>
<url-pattern>/join/*</url-pattern>
</servlet-mapping>
3. MemberDTO, MemberDAO 생성하기
com.join패키지를 만들고 안에 DAO, DTO를 생성합니다. 여기에 Servlet 클래스도 만들어서 넣을 예정입니다.
MemberDTO
package com.join;
public class MemberDTO {
private String userId;
private String userPwd;
private String userName;
private String userBirth; //애는 DATE로 만들어서 반드시 날짜를 넣어줘야한다.
private String userTel;
//getter/setter 생성
}
MemberDAO
package com.join;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class MemberDAO {
private Connection conn;
public MemberDAO(Connection conn) {
this.conn = conn;
}
//회원가입
public int sertData(MemberDTO dto) {
int result = 0;
PreparedStatement pstmt = null;
String sql;
try {
//이 sql문을 가지고
sql = "insert into member (userId,userPwd,userName,";
sql +="userBirth,userTel) values (?,?,?,?,?)";
//여기서 컬럼명이 맞는 검증
pstmt = conn.prepareStatement(sql);
//완벽한 insert 문
pstmt.setString(1, dto.getUserId());
pstmt.setString(2, dto.getUserPwd());
pstmt.setString(3, dto.getUserName());
pstmt.setString(4, dto.getUserBirth());
pstmt.setString(5, dto.getUserTel());
//DB에 가서 실행해라
result = pstmt.executeUpdate();
//DB사용했으면 닫아준다.
pstmt.close();
} catch (Exception e) {
System.out.println(e.toString());
}
return result;
}
//데이터 읽어오기(읽기) - 하나의 데이터만 읽으면 된다(로그인할 때)
public MemberDTO getReadData(String userId) {
MemberDTO dto = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql;
try {
//userId로 select 해온다.
sql = "select userId,userPwd,userName,userBirth,";
sql+= "userTel from member where userId=?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, userId);
rs = pstmt.executeQuery();
//if문 안에들어왔다는 것은 데이터가 있다는 뜻
if(rs.next()) {
dto = new MemberDTO();
dto.setUserId(rs.getString("userId"));
dto.setUserPwd(rs.getString("userPwd"));
dto.setUserName(rs.getString("userName"));
dto.setUserBirth(rs.getString("userBirth"));
dto.setUserTel(rs.getString("userTel"));
}
//dto에 데이터를 넣었으니 닫아준다
rs.close();
pstmt.close();
} catch (Exception e) {
System.out.println(e.toString());
}
return dto;
}
}
4. Servlet 클래스 생성 - MemberServlet.java
- 회원가입 시 포워드(forward) 페이지 호출
package com.join;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MemberServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
protected void forward(HttpServletRequest req, HttpServletResponse resp, String url) throws ServletException, IOException {
RequestDispatcher rd = req.getRequestDispatcher(url);
rd.forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
JSP 페이지 작성
created.jsp
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
request.setCharacterEncoding("UTF-8");
String cp = request.getContextPath();
%>
<!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>회원가입</title>
<link rel="stylesheet" type="text/css" href="<%=cp%>/member/css/style.css">
<link rel="stylesheet" type="text/css" href="<%=cp%>/member/css/created.css">
<script type="text/javascript" src="<%=cp%>/member/js/util.js"></script>
<script type="text/javascript">
function sendIt() {
var f = document.myForm;
str = f.userId.value;
str = str.trim();
if(!str) {
alert("아이디를 입력하세용!");
f.userId.focus();
return;
}
f.userId.value = str;
str = f.userPwd.value;
str = str.trim();
if(!str) {
alert("패스워드를 입력하세용!");
f.userPwd.focus();
return;
}
f.userPwd.value = str;
f.action = "<%=cp%>/join/created_ok.do";
f.submit();
}
</script>
</head>
<body>
<div id="bbs">
<div id="bbs_title">
회원가입
</div>
<form action="" method="post" name="myForm">
<div id="bbsCreated">
<div class="bbsCreated_bottomLine">
<dl>
<dt>아 이 디</dt>
<dd>
<input type="text" name="userId" size="35" maxlength="20"
class="boxTF">
</dd>
</dl>
</div>
<div class="bbsCreated_bottomLine">
<dl>
<dt>패스워드</dt>
<dd>
<input type="text" name="userPwd" size="35" maxlength="20"
class="boxTF">
</dd>
</dl>
</div>
<div class="bbsCreated_bottomLine">
<dl>
<dt>이 름</dt>
<dd>
<input type="text" name="userName" size="35"
maxlength="50"class="boxTF">
</dd>
</dl>
</div>
<div class="bbsCreated_bottomLine">
<dl>
<dt>생 일</dt>
<dd>
<input type="text" name="userBirth" size="35"
maxlength="50"class="boxTF">
</dd>
</dl>
</div>
<div class="bbsCreated_bottomLine">
<dl>
<dt>전 화</dt>
<dd>
<input type="text" name="userTel" size="35"
maxlength="50"class="boxTF">
</dd>
</dl>
</div>
</div>
<div id="bbsCreated_footer">
<input type="button" value=" 가입하기 " class="btn2"
onclick="sendIt();"/>
<input type="reset" value=" 다시입력 " class="btn2"
onclick="document.myForm.userId.focus();"/>
<input type="button" value=" 가입취소 " class="btn2"
onclick="javascript:location.href='<%=cp%>'"/>
</div>
</form>
</div>
</body>
</html>
login.jsp
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
request.setCharacterEncoding("UTF-8");
String cp = request.getContextPath();
%>
<!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>로그인</title>
<link rel="stylesheet" type="text/css" href="<%=cp %>/member/css/style.css" >
<script type="text/javascript">
function login() {
var f = document.myForm;
if(!f.userId.value) {
alert("아이디를 입력하세요.");
f.userId.focus();
return;
}
if(!f.userPwd.value) {
alert("패스워드를 입력하세요.");
f.userPwd.focus();
return;
}
f.action = "<%=cp%>/join/login_ok.do";
f.submit();
}
</script>
</head>
<body>
<br/><br/>
<center>
<form action="" method="post" name="myForm">
<table align="center" cellpadding="0" cellspacing="0">
<tr height="2"><td colspan="2" bgcolor="#cccccc"></td></tr>
<tr height="30">
<td colspan="2" align="center">
<b>로그인</b>
</td>
</tr>
<tr height="2"><td colspan="2" bgcolor="#cccccc"></td></tr>
<tr height="25">
<td width="80" bgcolor="#e6e4e6" align="center">아이디</td>
<td width="120" style="padding-left: 5px;">
<input type="text" name="userId" maxlength="10" size="15"/>
</td>
</tr>
<tr height="25">
<td width="80" bgcolor="#e6e4e6" align="center">패스워드</td>
<td width="120" style="padding-left: 5px;">
<input type="password" name="userPwd" maxlength="10" size="15"/>
</td>
</tr>
<tr height="2"><td colspan="2" bgcolor="#cccccc"></td></tr>
<tr height="30">
<td colspan="2" align="center">
<input type="button" value="로그인" class="btn2" onclick="login();">
<input type="button" value="취소" class="btm2"
onclick="javascript:location.href='<%=cp%>/'">
<input type="button" value=" 회원가입 " class="btm2"
onclick="javascript:location.href='<%=cp%>/join/created.do';">
</td>
</tr>
<tr height="30">
<td colspan="2" align="center">
<font color="red"><b>${message }</b></font> <!-- el로 받았으니까 서블릿에서 받아올것이다 -->
<font color="red"><b>${message2 }</b></font>
<font color="red"><b>${message3 }</b></font>
</td>
</tr>
<!-- 비밀번호 찾기 만들기 -->
<tr height="2" ><td colspan="2" bgcolor="#cccccc"></td></tr>
<tr height="30">
<td colspan="2" align="center">
<a href="javascript:location.href='<%=cp %>/join/searchpw.do';">비밀번호 찾기</a>
</td>
</tr>
<tr height="2"><td colspan="2" bgcolor="#cccccc"></td></tr>
</table>
</form>
</body>
</html>
searchpw.jsp
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
request.setCharacterEncoding("UTF-8");
String cp = request.getContextPath();
%>
<!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>비밀번호찾기</title>
<link rel="stylesheet" type="text/css"href="<%=cp%>/member/css/style.css" />
<link rel="stylesheet" type="text/css"href="<%=cp%>/member/css/created.css" />
<script type="text/javascript">
function sendIt(){
var f = document.myForm;
if(!f.userId.value){
alert("아이디를 입력하세요!");
f.userId.focus();
return;
}
if(!f.userTel.value){
alert("패스워드를 입력하세요!");
f.userTel.focus();
return;
}
f.action = "<%=cp %>/join/searchpw_ok.do";
f.submit();
}
</script>
</head>
<body>
<br/><br/>
<form action="" method="post" name="myForm">
<table align="center" cellpadding="0" cellspacing="0">
<tr height="2"><td colspan="2" bgcolor="#cccccc"></tr>
<tr height="30">
<td colspan="2" align="center">
<b>비밀번호 찾기</b>
</td>
</tr>
<tr height="2"><td colspan="2" bgcolor="#cccccc"></tr>
<tr height="25">
<td width="80" bgcolor="#e6e4e6" align="center">아이디</td>
<td width="120" style="padding-left: 5px;">
<input type="text" name="userId" maxlength="10" size="15"/>
</td>
</tr>
<tr height="2"><td colspan="2" bgcolor="#cccccc"></tr>
<tr height="25">
<td width="80" bgcolor="#e6e4e6" align="center">전화번호</td>
<td width="120" style="padding-left: 5px;">
<input type="text" name="userTel" maxlength="13" size="15"/>
</td>
</tr>
<tr height="2"><td colspan="2" bgcolor="#cccccc"></tr>
<tr height="30">
<td colspan="2" align="center">
<input type="button" value="확인" class="btn2" onclick="sendIt();">
<input type="button" value="취소" class="btn2"
onclick="javascript:location.href='<%=cp %>/join/login.do';">
</td>
</tr>
<tr height="30">
<td colspan="2" align="center">
<font color="red"><b>${message }</b></font>
</td>
</tr>
<c:choose>
<c:when test="${!empty message}">
<tr height="1"><td colspan="2" bgcolor="#cccccc"></tr>
<tr><td align="center" colspan="2">
<a href="<%=cp %>/join/searchpw.do;">비밀번호 찾기</a>
</td></tr>
<tr height="1"><td colspan="2" bgcolor="#cccccc"></tr>
</c:when>
</c:choose>
</table>
</form>
</body>
</html>
updated.jsp
<%@ page contentType="text/html; charset=UTF-8"%>
<%
request.setCharacterEncoding("UTF-8");
String cp = request.getContextPath();
%>
<!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>회원수정</title>
<link rel="stylesheet" type="text/css"href="<%=cp%>/member/css/style.css" />
<link rel="stylesheet" type="text/css"href="<%=cp%>/member/css/created.css" />
<script type="text/javascript" src="<%=cp%>/member/js/util.js"></script>
<script type="text/javascript">
function sendIt(){
var f = document.myForm;
str = f.userPwd.value;
if(!str){
alert("패스워드를 입력하세요");
f.userPwd.focus();
return;
}
f.userPwd.value = str;
str = f.userBirth.value;
if(!str){
alert("생년월일을 입력하세요");
f.userBirth.focus();
return;
}
f.userBirth.value = str;
str = f.userTel.value;
if(!str){
alert("연락처를 입력하세요");
f.userTel.focus();
return;
}
f.userTel.value = str;
f.action = "<%=cp%>/join/updated_ok.do";
f.submit();
}
</script>
</head>
<body>
<div id="bbs">
<div id="bbs_title">회원수정</div>
<form action="" method="post" name="myForm">
<div id="bbsCreated">
<div class="bbsCreated_bottomLine">
<dl>
<dt>아 이 디</dt>
<dd>
${dto.userId }
</dd>
</dl>
</div>
<div class="bbsCreated_bottomLine">
<dl>
<dt>이 름</dt>
<dd>
${dto.userName }
</dd>
</dl>
</div>
<div class="bbsCreated_bottomLine">
<dl>
<dt>패스워드</dt>
<dd>
<input type="text" name="userPwd" size="35" maxlength="20"
value="${dto.userPwd }" class="boxTF" />
</dd>
</dl>
</div>
<div class="bbsCreated_bottomLine">
<dl>
<dt>
생 일
</dt>
<dd>
<input type="text" name="userBirth" size="35" maxlength="50"
value="${dto.userBirth }" class="boxTF" /><b>[YYYY-MM-DD]</b>
</dd>
</dl>
</div>
<div class="bbsCreated_bottomLine">
<dl>
<dt>
전 화
</dt>
<dd>
<input type="text" name="userTel" size="35" maxlength="50"
value="${dto.userTel }" class="boxTF" />
</dd>
</dl>
</div>
</div>
<div id="bbsCreated_footer">
<input type="button" value="수정하기" class="btn2" onclick="sendIt()" />
<input type="button" value="수정취소" class="btn2"
onclick="javascript:location.href='<%=cp %>';" />
</div>
</form>
</div>
</body>
</html>
index.jsp
<%@page import="com.join.CustomInfo"%>
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
request.setCharacterEncoding("UTF-8");
String cp = request.getContextPath();
//이건 JSP에서 썻던 방법 우리는 EL로 할 것이다
//CustomInfo info = (CustomInfo)session.getAttribute("customInfo");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSP/Servlet 게시판 목록</title>
</head>
<body>
<c:choose>
<c:when test="${empty sessionScope.customInfo.userId }">
<b>로그인하면 새로운 세상이 보입니다.</b><br/><br/>
</c:when>
<c:otherwise>
${sessionScope.customInfo.userName }님 방가방가..<br/><br/>
</c:otherwise>
</c:choose>
<c:choose>
<c:when test="${empty sessionScope.customInfo.userId }">
1. 성적처리(JSP)<br/>
2. 게시판(JSP)<br/>
3. 방명록(JSP)<br/>
4. 성적처리(Servlet)<br/>
</c:when>
<c:otherwise>
1. <a href="<%=cp%>/score/list.jsp">성적처리(JSP)</a><br/>
2. <a href="<%=cp%>/board/list.jsp">게시판(JSP)</a><br/>
3. <a href="<%=cp%>/guest/guest.jsp">방명록(JSP)</a><br/>
4. <a href="<%=cp%>/jumsu/list.do">성적처리(Servlet)</a><br/>
</c:otherwise>
</c:choose>
5. <a href="<%=cp%>/sboard/list.do">게시판(Servlet)</a><br/>
<br/><br/>
<c:choose>
<c:when test="${empty sessionScope.customInfo.userId }">
<a href="<%=cp %>/join/created.do">회원가입</a><br/>
<a href="<%=cp %>/join/login.do">로그인</a><br/>
</c:when>
<c:otherwise>
<a href="<%=cp %>/join/updated.do">정보수정</a><br/>
<a href="<%=cp %>/join/logout.do">로그아웃</a><br/>
</c:otherwise>
</c:choose>
<%-- ${name } --%>
</body>
</html>
로그인 성공 시 지금까지 만들었던 JSP & Servlet 게시판으로 갈 수 있는 링크가 보이게 된다.
로그인하기 전에는 5번 게시판만 링크 이동이 가능하다.
반응형
'Back-End > JSP & Struts & JDBC' 카테고리의 다른 글
[Servlet] 쿠키(cookie), 파일 업로드(1) - 파일 등록 및 조회, 파일 업로드(2) - 파일 업로드, 다운로드, 삭제 (0) | 2022.02.24 |
---|---|
[JSP & Servlet] 핵심&필수 개념 정리 - (복습) (0) | 2022.02.23 |
[Servlet] 성적 처리 리스트 (0) | 2022.02.22 |
[Servlet] 게시판 (0) | 2022.02.21 |
[Servlet] 서블릿 구조, EL, JSTl (0) | 2022.02.18 |
블로그의 정보
무작정 개발
무작정 개발