[Servlet&JSP] Chap 6-2. JSPを使用した実装メンバーCRUD(ログイン)


ログインロジック
  • ユーザーはindexです.jspページでID、PWを入力し、ログインボタンをクリックします
    -> memberLogin.jsp移動
  • memberLogin.jspでログインしたビジネスロジックを処理する
    -> Service -> DAO -> DB
  • memberLogin.jspがビジネスロジックを処理した後、返された値を使用してログインの成功/失敗を検証し、indexを実行します.jspに移動
  • 成功:サーバ側に情報を格納(session.setAttribute()メソッドを使用)
  • index.jspでsessionオブジェクトに格納されている値(session.getAttribute()メソッド)を確認してページを移動
  • メンバーオブジェクト:登録祝賀メッセージ、登録抹消
  • null:ログイン失敗メッセージ、ログインフォーム
  • をクリックしてログアウトします.jspの移動
  • セッションの破棄(session.invalidate()メソッド)
  • index.jspページ
  • に移動
    index.jsp
    <%@page import="kr.or.test.member.model.vo.Member"%>
    <%@ page language="java" contentType="text/html; charset=UTF-8"
    	pageEncoding="UTF-8"%>
    <!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>Insert title here</title>
    </head>
    <body>
    
    	<h1>혀니의 메인 페이지</h1>
    	
    	
    	<%
    		Member m = (Member)session.getAttribute("member");
    		
    		//session에서 'memeber'라는 key를 가지고, 데이터를 꺼냈을때
    		// 2가지 경우가 있다.
    		// 1. Member 객체가 정상적으로 있는 경우(로그인을 한 사람인 경우)
    		// 2. null 인 경우(로그인을 실행하였거나 혹은 로그인을 하지 않은 경우)
    	%>
    	
    	<%if(m!=null){ %>
    		[<%=m.getUserName() %>]님 환영합니다 <a href="/views/member/logout.jsp">로그아웃</a> <br>
    	<%} else{%>
    		<form action="/views/member/memberLogin.jsp" method="post">
    		<fieldset style="width:300px;">
    			<legend>로그인</legend>
    			ID : <input type="text" name="userId" placeholder="ID를 입력하세요"><br>
    			PW : <input type="password" name="userPwd" placeholder="패스워드를 입력하세요"><br>
    			<input type="submit" value="로그인">
    			</fieldset>
    		</form>	
    		<a href="/views/member/memberJoinUs.html">회원 가입</a>
    	<%} %>
    
    </body>
    </html>
    memberLogin.jsp
    <%@page import="kr.or.test.member.model.vo.Member"%>
    <%@page import="kr.or.test.member.model.service.MemberServiceImpl"%>
    <%@page import="kr.or.test.member.model.service.MemberService"%>
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!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>Insert title here</title>
    </head>
    <body>
    	
    	<%
    		String userId=request.getParameter("userId");
    		String userPwd=request.getParameter("userPwd");
    		
    		// 로그인 비즈니스 로직 처리
    		MemberService mService=new MemberServiceImpl();
    		Member m = mService.selectOneIdPwdSearch(userId, userPwd);
    	%>
    	
    	<%if(m!=null){ //로그인을 성공했다면
    		
    		// 서버측에 정보 저장
    		session.setAttribute("member", m);
    		
    	%>
    		
    		
    	<%}else{ //로그인을 실패했다면%>
    		<script>
    			alert('로그인 실패(ID 또는 PW 재확인 바람)');
    		</script>
    	
    	<%} %>
    	
    	<script>
    		location.replace('/');
    	
    	</script>
    	
    </body>
    </html>
    MemberService.java
    package kr.or.test.member.model.service;
    
    import kr.or.test.member.model.vo.Member;
    
    public interface MemberService {
    	
    	public Member selectOneIdPwdSearch(String userId, String userPwd);
    }
    MemberServiceImpl.java
    package kr.or.test.member.model.service;
    
    import java.sql.Connection;
    
    import kr.or.test.common.JDBCTemplate;
    import kr.or.test.member.model.dao.MemberDAO;
    import kr.or.test.member.model.vo.Member;
    
    public class MemberServiceImpl implements MemberService {
    
    	private MemberDAO mDAO = new MemberDAO();
    
    	@Override
    	public Member selectOneIdPwdSearch(String userId, String userPwd) {
    
    		Connection conn = JDBCTemplate.getConnection();
    		Member m = mDAO.selectOneIdPwdSearch(userId, userPwd, conn);
    
    		JDBCTemplate.close(conn);
    
    		return m;
    	}
    }
    MemberDAO.java
    package kr.or.test.member.model.dao;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    import kr.or.test.common.JDBCTemplate;
    import kr.or.test.member.model.vo.Member;
    
    public class MemberDAO {
    
    	public Member selectOneIdPwdSearch(String userId, String userPwd, Connection conn) {
    
    		PreparedStatement pstmt = null;
    		ResultSet rset = null;
    		Member m = null;
    
    		String sql = "SELECT * FROM MEMBER WHERE userId=? AND userPwd=? AND end_YN='N'";
    
    		try {
    			pstmt = conn.prepareStatement(sql);
    			pstmt.setString(1, userId);
    			pstmt.setString(2, userPwd);
    
    			rset = pstmt.executeQuery();
    
    			if (rset.next()) {
    				m = new Member();
    				m.setUserId(rset.getString("userId"));
    				m.setUserPwd(rset.getString("userPwd"));
    				m.setUserName(rset.getString("userName"));
    				m.setAge(rset.getInt("age"));
    				m.setEmail(rset.getString("email"));
    				m.setPhone(rset.getString("phone"));
    				m.setHobby(rset.getString("hobby"));
    				m.setAddress(rset.getString("address"));
    				m.setGender(rset.getString("gender").charAt(0));
    				m.setEnrollDate(rset.getDate("enrollDate"));
    				m.setEndYN(rset.getString("end_YN").charAt(0));
    			}
    
    		} catch (SQLException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} finally {
    			JDBCTemplate.close(rset);
    			JDBCTemplate.close(pstmt);
    		}
    
    		return m;
    
    	}
    
    }
    JDBCTemplate.java
    package kr.or.test.common;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    public class JDBCTemplate {
    
    	// getConnection
    	public static Connection getConnection() {
    
    		Connection conn = null;
    
    		try {
    			Class.forName("oracle.jdbc.driver.OracleDriver");
    
    			conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "jsp", "jsp");
    
    			conn.setAutoCommit(false);
    
    		} catch (ClassNotFoundException e) {
    
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (SQLException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		return conn;
    	}
    
    	// commit
    	public static void commit(Connection conn) {
    		try {
    			conn.commit();
    		} catch (SQLException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    
    	// rollback
    	public static void rollback(Connection conn) {
    		try {
    			conn.rollback();
    		} catch (SQLException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    	
    
    	// close(Statement)
    	public static void close(Statement stmt) {
    		try {
    			stmt.close();
    		} catch (SQLException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    
    	// close(ResultSet)
    	public static void close(ResultSet rset) {
    		try {
    			rset.close();
    		} catch (SQLException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    
    	// close(Connection)
    	public static void close(Connection conn) {
    		try {
    			conn.close();
    		} catch (SQLException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    
    }
    Member.java
    package kr.or.test.member.model.vo;
    
    import java.sql.Date;
    
    public class Member {
    	private String userId;
    	private String userPwd;
    	private String userName;
    	private int age;
    	private String email;
    	private String phone;
    	private String address;
    	private char gender;
    	private String hobby;
    	private Date enrollDate;
    	private char endYN;
    
    	public Member() {
    		super();
    		// TODO Auto-generated constructor stub
    	}
    
    	public Member(String userId, String userPwd, String userName, int age, String email, String phone, String address,
    			char gender, String hobby, Date enrollDate, char endYN) {
    		super();
    		this.userId = userId;
    		this.userPwd = userPwd;
    		this.userName = userName;
    		this.age = age;
    		this.email = email;
    		this.phone = phone;
    		this.address = address;
    		this.gender = gender;
    		this.hobby = hobby;
    		this.enrollDate = enrollDate;
    		this.endYN = endYN;
    	}
    	
    	
    	//  회원 가입시에 필요한 데이터만 저장하기 위한 생성자
    	public Member(String userId, String userPwd, String userName, int age, String email, String phone, String address,
    			char gender, String hobby) {
    		super();
    		this.userId = userId;
    		this.userPwd = userPwd;
    		this.userName = userName;
    		this.age = age;
    		this.email = email;
    		this.phone = phone;
    		this.address = address;
    		this.gender = gender;
    		this.hobby = hobby;
    	}
    
    	public String getUserId() {
    		return userId;
    	}
    
    	public void setUserId(String userId) {
    		this.userId = userId;
    	}
    
    	public String getUserPwd() {
    		return userPwd;
    	}
    
    	public void setUserPwd(String userPwd) {
    		this.userPwd = userPwd;
    	}
    
    	public String getUserName() {
    		return userName;
    	}
    
    	public void setUserName(String userName) {
    		this.userName = userName;
    	}
    
    	public int getAge() {
    		return age;
    	}
    
    	public void setAge(int age) {
    		this.age = age;
    	}
    
    	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 String getAddress() {
    		return address;
    	}
    
    	public void setAddress(String address) {
    		this.address = address;
    	}
    
    	public char getGender() {
    		return gender;
    	}
    
    	public void setGender(char gender) {
    		this.gender = gender;
    	}
    
    	public String getHobby() {
    		return hobby;
    	}
    
    	public void setHobby(String hobby) {
    		this.hobby = hobby;
    	}
    
    	public Date getEnrollDate() {
    		return enrollDate;
    	}
    
    	public void setEnrollDate(Date enrollDate) {
    		this.enrollDate = enrollDate;
    	}
    
    	public char getEndYN() {
    		return endYN;
    	}
    
    	public void setEndYN(char endYN) {
    		this.endYN = endYN;
    	}
    
    }