본문 바로가기
Java Web Programming/4. JSP

[JSP] 회원 관리 웹 어플리케이션 (EL/JSTL 적용, 웹 프로그램 경로, BootStrap + Model2 설계)

by 파프리카_ 2020. 9. 18.
728x90
반응형

[ 웹 프로그램 경로 ]

> Client

client 측에 도달되는 HTML, CSS, JavaScript는 / 를 명시할 경우 port 다음으로 정보를 찾게 된다.

 

> Server 

sever 측에서 실행되는 <%jsp: forward%>, <%jsp: include>(or JSTL <c:import>)는 

/ 를  명시할 경우 자신의 웹 컨텍스트(웹 어플리케이션 명) 다음에서 정보를 찾게 된다.

 

> 즉,

html, javaScript, css 는 ${pageContext.request.contextPath}/ 를 명시해서  - 절대경로

웹 어플리케이션 아래에서 정보를 찾게하면 된다.


[ 프로그램 진행 원리 및 개요 ]

JSTL / EL 표현 + Model2 설계방식 ( + MVC / Singleton / Front Controller Pattern 적용)

+ Bootstrap + 경로지정

 

1번 기능 : (회원 검색) id로 멤버 상세 정보 검색 기능

 


2번 기능 : 주소 종류를 제공하는 기능


3번 기능 :  옵션에 선택된 주소로 회원 정보를 검색하는 기능


4번 + 5번 기능 :  로그인 + 로그아웃 기능


[ 구현 코드 ] 

 Model

/MemberVO.java

package org.kosta.model;

public class MemberVO {
	private String id;
	private String password;
	private String name;
	private String address;
	
	
	public MemberVO() {
		super();
	}

	public MemberVO(String id, String password, String name, String address) {
		super();
		this.id = id;
		this.password = password;
		this.name = name;
		this.address = address;
	}

	@Override
	public String toString() {
		return "MemberVO [id=" + id + ", password=" + password + ", name=" + name + ", address=" + address + "]";
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}
	
	
}

 

/MemberDAO.java

package org.kosta.model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.sql.DataSource;

public class MemberDAO {
	private static MemberDAO instance = new MemberDAO();
	private DataSource dataSource; //DBCP
	
	private MemberDAO() {
		this.dataSource = DataSourceManager.getInstance().getDataSource();
	}

	public static MemberDAO getInstance() {
		return instance;
	}
	
	public void closeAll(PreparedStatement pstmt, Connection con) throws SQLException {
		if (pstmt != null)
			pstmt.close();
		if (con != null)
			con.close();
	}
	
	public void closeAll(ResultSet rs, PreparedStatement pstmt, Connection con) 
			throws SQLException {
		if (rs != null)
			rs.close();
		closeAll(pstmt, con);
	}
	
	
	/*
	 * 0번 기능 : 첫 화면에 총 회원수 출력하기
	 * getMemberTotalCount() : int
	 */
	public int getMemberTotalCount() throws SQLException {
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		int count = 0;
		
		try {
			con = dataSource.getConnection();
			String sql = "SELECT COUNT(*) FROM web_member";
			pstmt = con.prepareStatement(sql);
			rs = pstmt.executeQuery();
			if (rs.next())
				count = rs.getInt(1);
					
		} finally {
			closeAll(rs, pstmt, con);
		}
		
		return count;
	}
	
	
	/* 1번 기능 : id로 회원 정보 찾기
	 * findMemberById(String id) : MemberVO
	 */
	public MemberVO findMemberById(String id) throws SQLException {
		MemberVO vo = null;
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			con = dataSource.getConnection();
			String sql = "SELECT name, address FROM web_member "
					+ "WHERE id=?";
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, id);
			rs = pstmt.executeQuery();
			if (rs.next()) {
				vo = new MemberVO(id, null, rs.getString("name"), 
								rs.getString("address"));}
		} finally {
			closeAll(rs, pstmt, con);
		}
		
		return vo;
	}
	
	/* 2번 기능 : 회원 주소 종류 목록 보기
	 * getAddressKind() : ArrayList<String>
	 */
	public ArrayList<String> getAddressKind() throws SQLException{
		ArrayList<String> list = new ArrayList<String>();
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			con = dataSource.getConnection();
			String sql = "SELECT DISTINCT(address) FROM web_member";
			pstmt = con.prepareStatement(sql);
			rs = pstmt.executeQuery();
			while(rs.next()) {
				list.add(rs.getString(1));
			}
		} finally {
			closeAll(rs, pstmt, con);
		}
		return list;	
	}
	
	/* 3번 기능 : 주소로 회원정보(리스트로) 검색하기
	 * getMemberByAddress(String address) : ArrayList<MemberVO>
	 */
	public ArrayList<MemberVO> getMemberByAddress(String address) 
			throws SQLException {
		
		ArrayList<MemberVO> list = new ArrayList<MemberVO>();
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			con = dataSource.getConnection();
			String sql = "SELECT id, name FROM web_member "
					 + "WHERE address=?";
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, address);
			rs = pstmt.executeQuery();
			while(rs.next()) {
				list.add(new MemberVO(rs.getString("id"),null, 
								rs.getString("name"), null));
			}
		} finally {
			closeAll(rs, pstmt, con);
		}
		return list;	
	}
	
	/* 4번 기능 : 로그인 기능
	 * login(MemberVO) : void
	 */
	public MemberVO login(MemberVO vo) throws SQLException {
		MemberVO logvo = null;
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			con = dataSource.getConnection();
			String sql = "SELECT id, password, name, address FROM web_member "
					+ "WHERE id=? AND password=?";
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, vo.getId());
			pstmt.setString(2, vo.getPassword());
			rs = pstmt.executeQuery();
			if (rs.next()) {
				logvo = new MemberVO(rs.getString(1), rs.getString(2),
						rs.getString(3), rs.getString(4));
			}
			
		} finally {
			closeAll(rs, pstmt, con);
		}
		
		return logvo;
	}
	
	
	}//class

 


View

/index.jsp 

index를 실행하면 <jsp:forward> 방식으로 home.jsp로 간다

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" session="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<jsp:forward page="front">
	<jsp:param value="home" name="command"/>
</jsp:forward>

 

/error.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" session="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
	에러가 발생했습니다.<br>
	콘솔창을 확인하세요. <br>
	<img src="milk.jpg" width="300" height="400">
</div>
</body>
</html>

[ template ]

 

/home.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8" session="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>회원관리 HOME</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
	href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script
	src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script
	src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/myhome.css"/>

</head>
<body>
	<div class="container">

	<%-- "row", "col-[size]-[num] : 한 행의 열을 잡아줌 --%>
	
	<%-- Header 영역 --%>
	<div class="row header">
		<div class="col-sm-12">
			<%-- JSTL import --%>
			<c:import url="/template/header.jsp"></c:import>
		</div>
	</div>

	<%-- Main 화면 영역 --%>
	<div class="row main">
		<%-- Main 동작 영역 --%>
		<div class="col-sm-8">
			총 회원 수 : ${requestScope.totalCount} 명
		</div>
		
		<%-- Main 오른쪽 영역 --%>
		<div class="col-sm-4">
			<c:import url="/template/right.jsp"></c:import>
		</div>
	</div>
	
	<%-- Footer 영역 --%>
	<div class="row footer">
		<div class="col-sm-12">
			<c:import url="/template/footer.jsp"></c:import>
		</div>
	</div>
	
	
	</div>
</body>
</html>

 

/header.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" session="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%-- jsp:include or JSTL import 대상이므로, 
	 html 선언부는 정의하지 않는다--%>
<h3><a href="${pageContext.request.contextPath}/front?command=home">Home Logo</a></h3>

 

/footer.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" session="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%-- jsp:include or JSTL import 대상이므로, 
	 html 선언부는 정의하지 않는다--%>

경기도 성남시 분당구 삼평동 대왕판교로 670길 유스페이스2 B동 8층 TEL. 031-606-9311~20<br>
Copyright © 2020 KOSTA ALL RIGHTS RESERVED

 

/right.jsp (로그인/로그아웃 기능이 있어 밑에 기재되어 있음)


[ CSS ]

/myhome.css

@charset "UTF-8";
.header {
	/*문자 정렬 왼쪽*/
	text-align: left;
	height: 70px;
}

.main {
	text-align: center;
	height: 500px;
}

.footer {
	text-align: center;
	height: 10px;
}

--  기능 1  : '회원 검색' - id로 회원정보 조회

 

/findbyid-form.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8" session="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>회원관리 HOME</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
	href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script
	src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script
	src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/myhome.css"/>

</head>
<body>
	<div class="container">

	<%-- "row", "col-[size]-[num] : 한 행의 열을 잡아줌 --%>

	<%-- Header 영역 --%>
	<div class="row header">
		<div class="col-sm-12">
			<%-- JSTL import --%>
			<c:import url="/template/header.jsp"></c:import>
		</div>
	</div>

	<%-- Main 화면 영역 --%>
	<div class="row main">
		<%-- Main 동작 영역 --%>
		<div class="col-sm-8">
		
			<%-- findbyid-form 시작 --%>
			<form action="${pageContext.request.contextPath}/front">
				<input type="hidden" name="command" value="findMemberById">
				아이디 <input type="text" name="id">
				<input type="submit" value="검색">
			</form>
			<%-- findbyid-form 끝 --%>
			
		</div>
		
		<%-- Main 오른쪽 영역 --%>
		<div class="col-sm-4">
			<c:import url="/template/right.jsp"></c:import>
		</div>
	</div>
	
	<%-- Footer 영역 --%>
	<div class="row footer">
		<div class="col-sm-12">
			<c:import url="/template/footer.jsp"></c:import>
		</div>
	</div>
	
	
	</div>
</body>
</html>

 

/findbyid-ok.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" session="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>회원 상세 정보</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/myhome.css"/>
</head>
<body>
	<div class="container">

	<%-- "row", "col-[size]-[num] : 한 행의 열을 잡아줌 --%>

	<%-- Header 영역 --%>
	<div class="row header">
		<div class="col-sm-12">
			<%-- JSTL import --%>
			<c:import url="/template/header.jsp"></c:import>
		</div>
	</div>

	<%-- Main 화면 영역 --%>
	<div class="row main">
		<%-- Main 동작 영역 --%>
		<div class="col-sm-8">
		
				<%-- ok 부분 시작 --%>
				<h2>회원 상세 정보</h2> <br>
				아이디 : ${param.id}<br>
				이름 : ${requestScope.rvo.name}<br>
				주소 : ${requestScope.rvo.address}<br>
				<%-- ok 부분 끝 --%>
				
		</div>
		
		<%-- Main 오른쪽 영역 --%>
		<div class="col-sm-4">
			<c:import url="/template/right.jsp"></c:import>
		</div>
	</div>
	
	<%-- Footer 영역 --%>
	<div class="row footer">
		<div class="col-sm-12">
			<c:import url="/template/footer.jsp"></c:import>
		</div>
	</div>
	
	
	</div>
</body>
</html>

 

/findbyid-fail.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" session="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>회원 검색 실패</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/myhome.css"/>
</head>
<body>
	<div class="container">

	<%-- "row", "col-[size]-[num] : 한 행의 열을 잡아줌 --%>

	<%-- Header 영역 --%>
	<div class="row header">
		<div class="col-sm-12">
			<%-- JSTL import --%>
			<c:import url="/template/header.jsp"></c:import>
		</div>
	</div>

	<%-- Main 화면 영역 --%>
	<div class="row main">
		<%-- Main 동작 영역 --%>
		<div class="col-sm-8">
		
			<%-- fail 부분 시작 --%>
			<script>
				alert("${param.id} 아이디에 대한 회원정보가 없습니다.")
				location.href="${pageContext.request.contextPath}/index.jsp";
			</script>
			<%-- fail 부분 끝 --%>
			
		</div>
		
		<%-- Main 오른쪽 영역 --%>
		<div class="col-sm-4">
			<c:import url="/template/right.jsp"></c:import>
		</div>
	</div>
	
	<%-- Footer 영역 --%>
	<div class="row footer">
		<div class="col-sm-12">
			<c:import url="/template/footer.jsp"></c:import>
		</div>
	</div>
	
	
	</div>
</body>
</html>

--  기능 2 : 주소 종류를 테이블로 제공 

 

/address-list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8" session="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>회원관리 HOME</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
	href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script
	src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script
	src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/myhome.css"/>

</head>
<body>
	<div class="container">

	<%-- "row", "col-[size]-[num] : 한 행의 열을 잡아줌 --%>

	<%-- Header 영역 --%>
	<div class="row header">
		<div class="col-sm-12">
			<%-- JSTL import --%>
			<c:import url="/template/header.jsp"></c:import>
		</div>
	</div>

	<%-- Main 화면 영역 --%>
	<div class="row main">
		<%-- Main 동작 영역 --%>
		<div class="col-sm-8">
		
			<%-- addresslist-form 시작 --%>
			<h3>주소 목록</h3><br>
			<form action="${pageContext.request.contextPath}/front">
				<input type="hidden" name="command" value="findMemberListByAddress">
				
				<c:set var="addlist" value="${requestScope.AddList}"></c:set>
				
				<select required="required" name="address">
					<option value="">주소</option>
					
					<c:forEach items="${addlist}" var="addr">
						<option value="${addr}">${addr}</option>
					</c:forEach>
					
				</select>
				
				&nbsp;&nbsp;&nbsp;<input type="submit" value="검색">
				
			</form>
			<%-- addresslist-form 끝 --%>
			
		</div>
		
		<%-- Main 오른쪽 영역 --%>
		<div class="col-sm-4">
			<c:import url="/template/right.jsp"></c:import>
		</div>
	</div>
	
	<%-- Footer 영역 --%>
	<div class="row footer">
		<div class="col-sm-12">
			<c:import url="/template/footer.jsp"></c:import>
		</div>
	</div>
	
	
	</div>
</body>
</html>

--  기능 3 : 선택된 주소를 이용해 회원정보를 보여주는 기능

 

/findbyaddress-result.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8" session="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>회원관리 HOME</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
	href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script
	src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script
	src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/myhome.css"/>

</head>
<body>
	<div class="container">
	
	<%-- Header 영역 --%>
	<div class="row header">
		<div class="col-sm-12">
			<%-- JSTL import --%>
			<c:import url="/template/header.jsp"></c:import>
		</div>
	</div>

	<%-- Main 화면 영역 --%>
	<div class="row main">
		<%-- Main 동작 영역 --%>
		<div class="col-sm-6 col-sm-offset-2">
		
			<%-- memberlist 시작 --%>
				<h4>${param.address}에 사는 회원명단</h4>
				<table class="table table-hover table-bordered">
					<thead>
						<tr>
							<th>ID</th>
							<th>NAME</th>
						</tr>
					</thead>
					<c:forEach items="${requestScope.memberList}" var="m">
						<tr>
							<td>${m.id}</td>
							<td>${m.name}</td>
						</tr>
					</c:forEach>
				</table>
			<%-- memberlist-form-form 끝 --%>
			
		</div>
		
		<%-- Main 오른쪽 영역 --%>
		<div class="col-sm-4">
			<c:import url="/template/right.jsp"></c:import>
		</div>
	</div>
	
	<%-- Footer 영역 --%>
	<div class="row footer">
		<div class="col-sm-12">
			<c:import url="/template/footer.jsp"></c:import>
		</div>
	</div>
	
	
	</div>
</body>
</html>

 


-- 기능 4 : 로그인  + 로그아웃 기능 

 

/right.jsp

sessionScope를 쓸 때에는 JSP 선언부에 session="false"가 있으면 안된다 !

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>


<c:choose>
	<c:when test="${sessionScope.rvo != null}"> <%--session이 있으면 --%>
		${sessionScope.rvo.name}님 로그인 <br><br>
		<a href="${pageContext.request.contextPath}/front?command=logout">로그아웃</a><br><br>
	</c:when>
	<c:otherwise> <%-- session이 없으면 --%>
		<form action="${pageContext.request.contextPath}/front" method="post">
			<input type="hidden" name="command" value="login">
			<table>
				<tr>
					<td>아이디</td>
					<td><input type="text" name="id" required="required"></td>
				</tr>

				<tr>
					<td>패스워드</td>
					<td><input type="password" name="password" required="required"></td>
				</tr>

				<tr>
					<td colspan="2" align="right"><input type="submit" value="로그인">
					</td>
				</tr>
			</table>
		</form>

		<br>
	</c:otherwise>
</c:choose>

<a href="${pageContext.request.contextPath}/member/findbyid-form.jsp">회원검색</a>
<br>
<br>
<a href="${pageContext.request.contextPath}/front?command=getAddressKind">주소리스트</a>



 

/login-fail.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" session="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<script type="text/javascript">
	alert("로그인 실패했습니다.");
	location.href = "${pageContext.request.contextPath}/front?command=home";
</script>

Controller

/Controller.java

package org.kosta.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
 * 개별 Controller 객체를 표준화하는 interface
 */
public interface Controller {
	public String execute(HttpServletRequest request, HttpServletResponse response) 
		throws Exception;
}

 

/ HandlerMapping.java

package org.kosta.controller;
/*
 * 컨트롤러 객체 생성을 전담하는 Factory 객체
 * DispatcherSerlvet과 개별 Controller들과의 결합도를 낮추는 역할
 */
public class HandlerMapping {
	private static HandlerMapping instance = new HandlerMapping();
	private HandlerMapping() { }
	public static HandlerMapping getInstance() {
		return instance;
	}
	
	public Controller create(String command) {
		Controller controller = null;
		if (command.contentEquals("home"))
			controller = new HomeController();
		else if (command.contentEquals("findMemberById"))
			controller = new FindMemberByIdController();
		else if (command.contentEquals("getAddressKind"))
			controller = new GetAddressKindController();
		else if (command.contentEquals("findMemberListByAddress"))
			controller = new FindMemberByAddressController();
		else if (command.contentEquals("login"))
			controller = new LoginController();
		else if (command.contentEquals("logout"))
			controller = new LogoutController();
		return controller;
	}
}

 

/DispatcherServlet.java

handleRequest method 작동 방식

1. 에러(예외) 발생 시, 콘솔에 메세지 발생 경로 출력 후,  error.jsp로  redirect 방식으로 view로 이동한다.

2. 클라이언트가 전송한 command 정보를 받는다.

3. HandlerMapping 을 이용해 개별 컨트롤러 객체를 컨트롤러 인터페이스 타입으로 반환받는다.

4. 개별 컨트롤러를 실행한다.

5. 실행 후 반환된 String url 정보를 이용해,

     forward 방식 or redirect 방식으로 view로 이동해 응답하게 한다.

+ 각 단계에서 어디서 에러가 났는지 알 수 있도록 단계 별로 console에 print 되도록 해준다

package org.kosta.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;

/**
 */
@WebServlet("/front")
public class DispatcherServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	// doGet method
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.handleRequest(request, response);
	}

	// doPost method
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// POST 방식 한글처리
		request.setCharacterEncoding("utf-8");
		this.handleRequest(request, response);
	}

	// handle Request method
	protected void handleRequest(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			// 2. 클라이언트가 전송한 command 정보를 받는다.
			String command = request.getParameter("command");
			System.out.println("command: "+command);
			
			// 3. HandlerMapping 을 이용해 개별 컨트롤러 객체를 컨트롤러 인터페이스 타입으로 반환받는다.
			Controller controller = HandlerMapping.getInstance().create(command);
			System.out.println("controller: "+controller);
			
			// 4. 개별 컨트롤러를 실행하여, url을 반환받는다.
			String url = controller.execute(request, response);
			System.out.println("url: "+url);
			
			// 5. 실행 후 반환된 String url 정보를 이용해,
			// forward 방식 or redirect 방식으로 view로 이동해 응답하게 한다.
			if (url.startsWith("redirect:"))
				response.sendRedirect(url.substring(9));
			else
				request.getRequestDispatcher(url).forward(request, response);
			
		} catch (Exception e) {
			// 1. exception 발생 시, 콘솔에 에러 메세지 표시 후,
			// error.jsp로 redirect 방식으로 view에 띄워주기
			e.printStackTrace();
			response.sendRedirect("error.jsp");
		}
	}
}

---  기능 0 : index.jsp에서 실행하면,  HOME으로 이동 (총 회원수 반환) Controller

 

/HomeController.java

package org.kosta.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.kosta.model.MemberDAO;

public class HomeController implements Controller {

	@Override
	public String execute(HttpServletRequest request, HttpServletResponse response) 
			throws Exception {
		int count = MemberDAO.getInstance().getMemberTotalCount();
		request.setAttribute("totalCount", count);
		return "home.jsp";
	}
}

---  기능 1 : 아이디로 회원정보 조회 Controller

 

/FindMemberByIdController.java

package org.kosta.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.kosta.model.MemberDAO;
import org.kosta.model.MemberVO;

public class FindMemberByIdController implements Controller {

	@Override
	public String execute(HttpServletRequest request, HttpServletResponse response) 
			throws Exception {
		String url = "";
		String id = request.getParameter("id");
		
		MemberVO vo = MemberDAO.getInstance().findMemberById(id);
		
		//아래 jsp는 member 디렉토리 내에 있으므로,
		//path는 [directoryname]/[filename] 로 잡아줘야한다.
		if (vo != null) {
			request.setAttribute("rvo", vo);
			url = "member/findbyid-ok.jsp";
		} else {
			url = "member/findbyid-fail.jsp";
		}
		
		return url;
	}

}

---  기능 2 : 주소 종류를 제공하는 기능 Controller

 

/GetAddressKindController.java

package org.kosta.controller;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.kosta.model.MemberDAO;

public class GetAddressKindController implements Controller {

	@Override
	public String execute(HttpServletRequest request, HttpServletResponse response) 
			throws Exception {
		ArrayList<String> list= MemberDAO.getInstance().getAddressKind();
		if (list != null) {
			request.setAttribute("AddList", list);
		}
		return "member/address-list.jsp";
	}

}

---  기능 3 :  선택된 주소를 이용해 회원정보를 리스트로 반환받아 view에 전송해주는 기능 Controller

 

/FindMemberByAddressController.java

package org.kosta.controller;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.kosta.model.MemberDAO;
import org.kosta.model.MemberVO;

public class FindMemberByAddressController implements Controller {

	@Override
	public String execute(HttpServletRequest request, HttpServletResponse response) 
			throws Exception {
		
		String address = request.getParameter("address");
		
		ArrayList<MemberVO> list 
			= new ArrayList<MemberVO>(MemberDAO.getInstance().getMemberByAddress(address));
		
		request.setAttribute("memberList", list);

		return "member/findbyaddress-result.jsp";
	}

}

--  기능 4 : 로그인  Controller 

 

/LoginController.java

package org.kosta.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LogoutController implements Controller {

	@Override
	public String execute(HttpServletRequest request, HttpServletResponse response) 
			throws Exception {
		
		HttpSession session = request.getSession(false);
		if (session != null)
			session.invalidate();
		
		return "redirect:front?command=home";
	}

}

 

-- 기능 5 : 로그아웃  Controller

 

/LogoutController.java

package org.kosta.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LogoutController implements Controller {

	@Override
	public String execute(HttpServletRequest request, HttpServletResponse response) 
			throws Exception {
		
		HttpSession session = request.getSession(false);
		if (session != null)
			session.invalidate();
		
		return "redirect:index.jsp";
	}

}

[ 브라우저 화면 ] 

 

> Home (home.jsp)

 

> 1. 회원 검색 폼

 

> 1-1. 회원 검색 : 존재하는 아이디 검색했을 때, (findbyid-ok.jsp)

 

> 1-2. 회원 검색 :존재하지 않는 아이디 검색했을 때, (findbyid-fail.jsp)

 

> 2. '주소목록 보기' 클릭하면 보이는 주소 선택지 화면

 

> 3. select에서 option으로 주소를 선택했을 때 보여지는 회원 명단 

 

> 4-1. 로그인 성공 시,

 

> 4-2. 로그인 실패 시 -> index.jsp

728x90
반응형