gwooden_코린이
이클립스 JSP/서블릿 로그인 및 회원가입 페이지 구현해보기 본문
728x90
- index 페이지
- 로그인 페이지에서 회원가입 버튼을 클릭 - login.jsp
- 회원가입페이지 - join.jsp
- 아이디 입력하고 중복확인 버튼 누르면 중복검사
- idCheckServlet.java 구현
- 여기서 DAO에 confirmID 메서드로 중복확인 체크
- 중복확인버튼 클릭시 페이지 이동 member.js에서 구현
- 중복확인 버튼 클릭 후
- idCheck.jsp 페이지로 이동
- 회원가입 버튼
- JoinServlet.java, DAO에 insertMember 메서드로 구현
- 회원가입 성공시 로그인페이지로 or 회원가입 실패시 회원가입페이지로
- 로그아웃
main.jsp -> 로그아웃 버튼 -> 세션 삭제 -> 로그인 페이지
- 회원정보수정
main.jsp -> 회원정보수정버튼 -> update.do 서블릿
-> dao에 update 메서드 호출 -> 세션정보 변경
-> main.jsp
com.study.controller 패키지
더보기
package com.study.controller;
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.study.dao.MemberDAO;
@WebServlet("/idCheck.do")
public class IdCheckServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public IdCheckServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
MemberDAO dao = MemberDAO.getInstance();
int result = dao.confirmID(id);
request.setAttribute("id", id);
request.setAttribute("result", result);
RequestDispatcher dispatcher = request.getRequestDispatcher("member/idCheck.jsp");
dispatcher.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
package com.study.controller;
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.study.dao.MemberDAO;
import com.study.vo.MemberVO;
@WebServlet("/join.do")
public class joinServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public joinServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher dispatcher = request.getRequestDispatcher("member/join.jsp");
dispatcher.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String name = request.getParameter("name");
String id = request.getParameter("id");
String pw = request.getParameter("pw");
String email = request.getParameter("email");
String phone = request.getParameter("phone");
String admin = request.getParameter("admin");
MemberVO vo = new MemberVO();
vo.setName(name);
vo.setId(id);
vo.setPw(pw);
vo.setEmail(email);
vo.setPhone(phone);
vo.setAdmin(Integer.parseInt(admin));
MemberDAO dao = MemberDAO.getInstance();
// dao에서 insert 실행시키는 sql 작업
// 1 : 회원기입 성공 | 0 : 회원가입 실패
int result = dao.insertMember(vo);
String url = null;
if(result == 1) {
request.setAttribute("msg", "회원가입 성공!");
url = "member/login.jsp";
} else {
request.setAttribute("msg", "회원가입 실패!");
url = "member/join.jsp";
}
RequestDispatcher rd = request.getRequestDispatcher(url);
rd.forward(request, response);
}
}
package com.study.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
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 javax.servlet.http.HttpSession;
import com.study.dao.MemberDAO;
import com.study.vo.MemberVO;
/**
* Servlet implementation class LoginServlet
*/
@WebServlet("/login.do")
public class LoginServlet extends HttpServlet implements Servlet {
private static final long serialVersionUID = 1L;
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher dispatcher = request.getRequestDispatcher("member/login.jsp");
dispatcher.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String url = "member/login.jsp"; //로그인 실패시 이동할 페이지
String id = request.getParameter("id");
String pw = request.getParameter("pw");
MemberDAO dao = MemberDAO.getInstance();
// 여기는 dao에서 로그인 인증처리하는 메서드를 호출
//1 : 로그인 성공 | 0 : 비번 틀림 | -1 : 아이디 틀림
int result = dao.userCheck(id, pw);
if(result == 1) {
//로그인 성공 세션에 회원정보 등록
MemberVO vo = dao.getMember(id);
HttpSession session = request.getSession();
session.setAttribute("loginUser", vo);
url = "main.jsp"; //로그인 성공시 이동할 페이지
} else if(result == 0) {
request.setAttribute("msg", "비밀번호가 틀렸습니다.");
} else {
request.setAttribute("msg", "아이디가 틀렸습니다.");
}
RequestDispatcher dispatcher = request.getRequestDispatcher(url);
dispatcher.forward(request, response);
}
}
package com.study.controller;
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 javax.servlet.http.HttpSession;
@WebServlet("/logout.do")
public class LogoutServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LogoutServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
session.invalidate(); //세션 지우면서 로그아웃 처리됨
RequestDispatcher rd = request.getRequestDispatcher("member/login.jsp");
rd.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
package com.study.controller;
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 javax.servlet.http.HttpSession;
import com.study.dao.MemberDAO;
import com.study.vo.MemberVO;
@WebServlet("/update.do")
public class UpdateMemberServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public UpdateMemberServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
MemberDAO dao = MemberDAO.getInstance();
MemberVO vo = dao.getMember(id);
request.setAttribute("vo", vo);
RequestDispatcher rd = request.getRequestDispatcher("member/update.jsp");
rd.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
MemberVO vo = new MemberVO();
vo.setName(request.getParameter("name"));
vo.setId(request.getParameter("id"));
vo.setPw(request.getParameter("pw"));
vo.setEmail(request.getParameter("email"));
vo.setPhone(request.getParameter("phone"));
vo.setAdmin(Integer.parseInt(request.getParameter("admin")));
MemberDAO dao = MemberDAO.getInstance();
//업데이트 실행
dao.updateMember(vo);
HttpSession session = request.getSession();
session.setAttribute("loginUser", vo);
response.sendRedirect("main.jsp");
}
}
com.study.dao 패키지
더보기
package com.study.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import com.study.vo.MemberVO;
//싱글톤
public class MemberDAO {
//싱글콘은 생성자가 private
//그래야 다른 class나 등등에서 객체생성을 못함
private MemberDAO() {
}
//객체 생성 private 다른데에서 수정같은걸 못하게 방지
//static 정적 객체로 생성(메모리에 공유가 됨)
private static MemberDAO instance = new MemberDAO();
//생성한 객체를 호출(리턴)하는 메서드
//수정은 못함 get가능 (읽기전용)
public static MemberDAO getInstance() {
return instance;
}
//커넥션 풀 get하는 메서드
public Connection getConnection() throws Exception {
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/myoracle");
Connection conn = ds.getConnection();
return conn;
}
//아이디 비번 체크하는 메서드
public int userCheck(String id, String pw) {
int result = -1; //결과 저장 변수
String sql = "select pw from member where userid=?";
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, id);
rs = pstmt.executeQuery();
if(rs.next()) {
if(rs.getString("pw") != null && rs.getString("pw").equals(pw)) {
result = 1; //아이디 비번 모두 일치
} else {
result = 0; //아이디는 일치, 비번을 일치하지 않음
}
} else {
result = -1; //입력한 아이디가 없음
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(rs != null)
rs.close();
if(pstmt != null)
pstmt.close();
if(conn != null)
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
//로그인 성공한 사람의 정보를 빼오는 검색문
public MemberVO getMember(String id) {
MemberVO vo = null;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = "select * from member where userid = ?";
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, id);
rs = pstmt.executeQuery();
if(rs.next()) {
vo = new MemberVO();
vo.setName(rs.getString("name"));
vo.setId(rs.getString("userid"));
vo.setPw(rs.getString("pw"));
vo.setEmail(rs.getString("email"));
vo.setPhone(rs.getString("phone"));
vo.setAdmin(rs.getInt("admin"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(rs != null)
rs.close();
if(pstmt != null)
pstmt.close();
if(conn != null)
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return vo;
}
public int confirmID(String id) {
int result = -1; //중복 검사 결과 저장
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = "select userid from member where userid=?";
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, id);
rs = pstmt.executeQuery();
if(rs.next()) {
result = 1; //중복 아이디가 있음
} else {
result = -1; //중복된 아이디가 없음
}
} catch(Exception e) {
e.printStackTrace();
} finally {
try {
if(rs != null)
rs.close();
if(pstmt != null)
pstmt.close();
if(conn != null)
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
//insert 메서드
public int insertMember(MemberVO vo) {
int result = 0; //insert 실행 결과를 저장
Connection conn = null;
PreparedStatement pstmt = null;
String sql = "insert into member values(?, ?, ?, ?, ?, ?)";
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, vo.getName());
pstmt.setString(2, vo.getId());
pstmt.setString(3, vo.getPw());
pstmt.setString(4, vo.getEmail());
pstmt.setString(5, vo.getPhone());
pstmt.setInt(6, vo.getAdmin());
result = pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(pstmt != null)
pstmt.close();
if(conn != null)
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
//update 메서드
public void updateMember(MemberVO vo) {
Connection conn = null;
PreparedStatement pstmt = null;
String sql = "update member set name=?, pw=?, email=?, phone=?, admin=? where userid=?";
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, vo.getName());
pstmt.setString(2, vo.getPw());
pstmt.setString(3, vo.getEmail());
pstmt.setString(4, vo.getPhone());
pstmt.setInt(5, vo.getAdmin());
pstmt.setString(6, vo.getId());
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(pstmt != null)
pstmt.close();
if(conn != null)
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
com.study.vo 패키지
더보기
package com.study.vo;
public class MemberVO {
private String name;
private String id;
private String pw;
private String email;
private String phone;
private int admin;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPw() {
return pw;
}
public void setPw(String pw) {
this.pw = pw;
}
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 int getAdmin() {
return admin;
}
public void setAdmin(int admin) {
this.admin = admin;
}
}
- WebContent 풀더
- member 풀더
idCheck.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>중복확인 페이지</h1>
<c:if test="${result == 1}">
${id}는 <strong style="color: red">사용중인</strong> 아이디입니다.
</c:if>
<c:if test="${result == -1}">
${id}는 <strong style="color: blue">사용 가능한</strong> 아이디입니다.
<input type="button" value="사용" onclick="idOk()">
</c:if>
<script src="script/member.js"></script>
</body>
</html>
join.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>회원가입</h1>
<form method="post" action="join.do" name="frm">
이름 : <input type="text" name="name" ><br>
아이디 : <input type="text" name="id" >
<input type="button" value="중복확인" onclick="idCheck()"><br>
비밀번호 : <input type="password" name="pw" ><br>
비밀번호 확인 : <input type="password" name="pw_check"><br>
이메일 : <input type="text" name="email" ><br>
전화번호 : <input type="text" name="phone" ><br>
회원등급 : <input type="radio" name="admin" value="0" >일반회원
<input type="radio" name="admin" value="1" >관리자<br>
<input type="submit" value="회원가입" onclick="return loginCheck()">
</form>
<h3 style="color: red">${msg}</h3>
<script src="script/member.js"></script>
</body>
</html>
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>로그인 페이지</h1>
<form method="post" action="login.do" name="frm">
아이디 : <input type="text" name="id" > <br>
비밀번호 : <input type="password" name="pw" > <br><br>
<input type="submit" value="로그인" onclick="return loginCheck()">
<input type="button" value="회원가입" onclick="location.href='join.do'">
</form>
<h3 style="color:red" >${msg}</h3>
<script src="script/member.js"></script>
</body>
</html>
update.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>회원정보 수정 페이지</h1>
<form method="post" action="update.do">
이름 : <input type="text" name="name" value="${vo.name}"><br>
아이디 : <input style="background-color: lightgray" type="text" name="id" value="${vo.id}" readonly><br>
비밀번호 : <input type="password" name="pw"><br>
이메일 : <input type="text" name="email" value="${vo.email}"><br>
전환번호 : <input type="text" name="phone" value="${vo.phone}"><br>
권한 :
<c:choose>
<c:when test="${vo.admin == 0}">
<input type="radio" name="admin" value="0" checked >일반회원
<input type="radio" name="admin" value="1" >관리자
</c:when>
<c:otherwise>
<input type="radio" name="admin" value="0" >일반회원
<input type="radio" name="admin" value="1" checked >관리자
</c:otherwise>
</c:choose>
<br>
<input type="submit" value="수정">
</form>
</body>
</html>
- script 풀더
member.js
//로그인 아이디 유효성 검사
function loginCheck() {
if(document.frm.id.value.length == 0) {
alert("아이디 입력하세요.")
frm.id.focus();
return false; //submit 막는
}
//로그인 비밀번호 유효성 검사
if(document.frm.pw.value == "") {
alert("비밀번호 입력하세요.")
frm.pw.focus();
return false; //submit 막는
}
//둘다 만족했을 경우 sumbit 사용가능
return true;
}
//회원가입 아이디 중복 체크
function idCheck() {
if(document.frm.id.value.length == 0) {
alert("아이디 입력하세요.")
frm.id.focus();
return;
}
let url = "idCheck.do?id=" + document.frm.id.value;
window.open(url);
}
function idOk() {
self.close();
}
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>환영쓰</h1>
<a href="login.do">로그인페이지로 이동</a>
</body>
</html>
main.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>회원 페이지</h1>
<h3>${loginUser.name}(${loginUser.id})님 환영합니다.</h3>
<input type="button" value="로그아웃" onclick="location.href='logout.do'">
<input type="button" value="회원정보수정" onclick="location.href='update.do?id=${loginUser.id}'">
</body>
</html>
728x90
'JSP&Servlet' 카테고리의 다른 글
서블릿 파일 업로드 기능 구현 해보기 (0) | 2023.02.06 |
---|---|
이클립스 jsp/서블릿 (0) | 2023.02.01 |
데이터베이스 커넥션 풀 (DBCP) (0) | 2023.01.30 |
이클립스 JSP/서블릿 JDBC 사용해보기 (0) | 2023.01.27 |
서블릿 필터 기능 (0) | 2023.01.27 |
Comments