10일차_직원관리_Ajax, jQuery
---------------------------------
직원 관리 JSP(JDBC) 프로그램
11. 소스코드
//EmployeeInsertForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="com.test.*" %>
<%
StringBuilder positionList = new StringBuilder();
EmployeeDAO dao = new EmployeeDAO();
for (Position p : dao.positionList()) {
//<option> 태그 동적 생성 과정 추가
//<option value="직위번호">직위명</option>
positionList.append(String.format(""));
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>직원관리(JSP버전)</title>
<link rel="stylesheet" type="text/css" href="TableStyle.css">
<link rel="stylesheet" type="text/css" href="DivStyle.css">
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#birthday").datepicker({
changeYear:true
, changeMonth: true
, dateFormat:"yy-mm-dd"
});
});
</script>
<script type="text/javascript">
//Javascript 버전
window.onload=function() {
//선택 목록에 체인지 이벤트 등록
document.getElementById("position").onchange=function() {
var positionId = document.getElementById("position").value;
//주의) Ajax 호출 기능이 있는 함수 호출시
//반환값 처리를 하지 않는다.
minBasicPay(positionId);
};
};
//선택된 jid(직위번호)에 대한 최소기본급(minBasicPay)검사
//-> JSP, Servlet, Ajax 기능 추가
function minBasicPay(positionId) {
var result = "";
//Ajax 요청 및 응답 메시지 처리
//1. XMLHttpRequest 객체 생성
var xmlhttp=new XMLHttpRequest();
//2. 콜백 함수 지정 (응답 처리 액션 함수)
xmlhttp.onreadystatechange=function() {
//5. 응답 메시지 처리 (문자열)
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
result = xmlhttp.responseText;
alert("Ajax 응답 도착 완료!"+result);
//주의) 이 위치에 결과 출력 과정 추가
document.getElementById("minBasicPay").innerHTML = result;
}
};
//3. 요청 주소 지정
xmlhttp.open("GET","PositionReceive.jsp?positionId="+positionId,true);
//4. Ajax 요청
xmlhttp.send();
alert("Ajax 요청 완료!");
//주의) 사용 금지
//return result;
}
</script>
</head>
<body>
<div>
<%--메뉴 영역--%>
<div class = "title">
<%--
동일한 메뉴 디자인을 여러 페이지에 적용한 경우
수정 사항이 발생하면 모든 페이지를 동일하게 수정해야 한다.
-> 동일한 메뉴 디자인을 별도의 페이지로 작성
-> 필요하는 페이지에 동적 삽입
--%>
<h1>직원관리 (JSP버전)</h1>
<c:import url="EmployeeMenu.jsp"></c:import>
</div>
<%--콘텐츠 영역--%>
<div class = "main">
<h2>[직원명단]</h2>
<form>
<%-- 직원명단 버튼은 식별자로 class 사용 --%>
<input type="button" value="직원명단" class="employeeList">
<input type="button" value="직원검색" id="employeeSearch">
</form>
<form action="EmployeeInsert.jsp" method="post">
<table id="t02">
<tr>
<th>이름</th>
<td><input type="text" id="name" name="name"></td>
</tr>
<tr>
<th>생년월일</th>
<td><input type="text" id="birthday" name="birthday">달력</td>
</tr>
<tr>
<th>양/음력</th>
<td><input type="radio">양력 <input type="radio">음력</td>
</tr>
<tr>
<th>전화번호</th>
<td><input type="text"></td>
</tr>
<tr>
<th>지역명</th>
<td><select><option>서울</option></select></td>
</tr>
<tr>
<th>부서명</th>
<td><select><option>개발부</option></select></td>
</tr>
<tr>
<th>직위명</th>
<td>
<select id="position">
<!--
<option>사원</option>
-->
<%=positionList.toString()%>
</select>
</td>
</tr>
<tr>
<th>기본급</th>
<td><input type="text">(최소 <span id="minBasicPay">0</span>원 이상)</td>
</tr>
<tr>
<th>수당</th>
<td><input type="text"></td>
</tr>
<tr>
<th></th>
<td><input type="submit" value="직원추가"></td>
</tr>
</table>
</form>
</div>
</div>
</body>
</html>
//EmployeeDAO.java
package com.test;
import java.sql.*;
import java.util.*;
public class EmployeeDAO {
//직원 명단 출력 메소드
public ArrayList<Employee>list(){
ArrayList<Employee> result = new ArrayList<Employee>();
Connection conn = null;
PreparedStatement pstmt = null;
try{
conn = DBConn.getConnection();
String sql = String.format("SELECT employeeId, name, birthday, lunar, lunarName, telephone, departmentId, departmentName, positionId, positionName, regionId, regionName, basicPay, extraPay, pay FROM employeeView ORDER BY employeeId");
pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
while(rs.next()){
Employee e = new Employee();
e.setEmployeeId(rs.getString("employeeId"));
e.setName(rs.getString("name"));
e.setBirthday(rs.getString("birthday"));
e.setLunar(rs.getInt("lunar"));
e.setLunarName(rs.getString("lunarName"));
e.setTelephone(rs.getString("telephone"));
e.setDepartmentId(rs.getString("departmentId"));
e.setDepartmentName(rs.getString("departmentName"));
e.setPositionId(rs.getString("positionId"));
e.setPositionName(rs.getString("positionName"));
e.setRegionId(rs.getString("regionId"));
e.setRegionName(rs.getString("regionName"));
e.setBasicPay(rs.getInt("basicPay"));
e.setExtraPay(rs.getInt("extraPay"));
e.setPay(rs.getInt("pay"));
result.add(e);
}
rs.close();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(pstmt != null){
pstmt.close();
}
}catch(Exception e){
}
DBConn.close();
}
return result;
}
//직원 검색 출력 메소드(검색기준 : 사번,주민번호,이름,지역,부서,직위)
public ArrayList<Employee> list(String searchKey, String searchValue){
ArrayList<Employee> result = new ArrayList<Employee>();
Connection conn = null;
PreparedStatement pstmt = null;
try{
conn = DBConn.getConnection();
String sql = String.format("SELECT employeeId, name, birthday, lunar, lunarName, telephone, departmentId, departmentName, positionId, positionName, regionId, regionName, basicPay, extraPay, pay FROM employeeView e");
switch(searchKey){
case "0" : sql += " WHERE employeeId=?"; break;
case "1" : sql += " WHERE ssn=encrypt(?, e.name)"; break;
case "2" : sql += " WHERE name=?"; break;
case "3" : sql += " WHERE regionName=?"; break;
case "4" : sql += " WHERE departmentName=?"; break;
case "5" : sql += " WHERE positionName=?"; break;
}
sql += " ORDER BY employeeId";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, searchValue);
ResultSet rs = pstmt.executeQuery();
while(rs.next()){
Employee e = new Employee();
e.setEmployeeId(rs.getString("employeeId"));
e.setName(rs.getString("name"));
e.setBirthday(rs.getString("birthday"));
e.setLunarName(rs.getString("lunarName"));
e.setTelephone(rs.getString("telephone"));
e.setDepartmentName(rs.getString("departmentName"));
e.setPositionName(rs.getString("positionName"));
e.setRegionName(rs.getString("regionName"));
e.setBasicPay(rs.getInt("basicPay"));
e.setExtraPay(rs.getInt("extraPay"));
e.setPay(rs.getInt("pay"));
result.add(e);
}
rs.close();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(pstmt != null){
pstmt.close();
}
}catch(Exception e){
}
DBConn.close();
}
return result;
}
//직원 전체 출력
public int count(){
int result = 0;
Connection conn = null;
PreparedStatement pstmt = null;
try{
conn = DBConn.getConnection();
String sql = String.format("select count(*) as \"count\" from employeeView");
pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
while(rs.next()){
result = rs.getInt("count");
}
rs.close();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(pstmt != null){
pstmt.close();
}
}catch(Exception e){
}
DBConn.close();
}
return result;
}
//직원 검색 결과 인원수 출력 메소드
public int count(String searchKey, String searchValue){
int result = 0;
Connection conn = null;
PreparedStatement pstmt = null;
try{
conn = DBConn.getConnection();
String sql = String.format("select count(*) as \"count\" from employeeView e");
switch(searchKey){
case "0" : sql += " WHERE employeeId=?"; break;
case "1" : sql += " WHERE ssn=encrypt(?, e.name)"; break;
case "2" : sql += " WHERE name=?"; break;
case "3" : sql += " WHERE regionName=?"; break;
case "4" : sql += " WHERE departmentName=?"; break;
case "5" : sql += " WHERE positionName=?"; break;
}
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, searchValue);
ResultSet rs = pstmt.executeQuery();
while(rs.next()){
result = rs.getInt("count");
}
rs.close();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(pstmt != null){
pstmt.close();
}
}catch(Exception e){
}
DBConn.close();
}
return result;
}
//직원 입력 메소드
public int add(Employee e) {
int result = 0;
/*
INSERT INTO employee (employeeId
,name
,ssn
,birthday
,lunar
,telephone
,departmentId
,positionId
,regionId
,basicPay
,extraPay)
VALUES (employeeSeq.nextval
, ?
, encrypt(?, ?)
, ? --'1980-12-12'
, ? --양력 0, 음력 1
, ? --'010-123-1234'
, ? --departmentId FK
, ? --positionId FK
, ? --regionId FK
, ?
, ?)
*/
//문제) 입력 관련 액션 추가
return result;
}
//직위 종류 출력 메소드
public ArrayList<Position> positionList() {
ArrayList<Position> result = new ArrayList<Position>();
//SELECT positionId, positionName, minBasicPay
// FROM position
// ORDER BY positionId
return result;
}
//최소 기본급 검색 메소드
public int getMinBasicPay(String jid) {
int result = 0;
//SELECT minBasicPay FROM position WHERE positionId=?
return result;
}
}
//PositionReceive.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="com.test.*" %>
<%
//데이터 수신 (positionId)
//데이터베이스 액션 -> getMinBasicPay() 메소드 호출
String result = "0";
//Ajax 응답
out.write(result);
%>
//EmployeeInsert.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="com.test.*" %>
<%
//데이터 수신
//데이터베이스 액션 -> add() 메소드 호출
//강제 페이지 전환
response.sendRedirect("EmployeeList.jsp");
%>
//EmployeeList.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import = "com.test.*" %>
<%@ taglib prefix = "c" uri ="http://java.sun.com/jsp/jstl/core" %>
<%
StringBuilder sb = new StringBuilder();
int count = 0;
EmployeeDAO dao = new EmployeeDAO();
count = dao.count();
for(Employee e : dao.list()){
//번호, 이름, 생일,양음력,전번,부서명,직위명,지역명,기본급,수당,급여,삭제
sb.append(String.format("<tr>\r\n"));
sb.append(String.format("<td>%s</td>", e.getEmployeeId() ));
sb.append(String.format("<td>%s</td>", e.getName() ));
sb.append(String.format("<td>%s</td>", e.getBirthday() ));
sb.append(String.format("<td>%s</td>", e.getLunarName() ));
sb.append(String.format("<td>%s</td>", e.getTelephone() ));
sb.append(String.format("<td>%s</td>", e.getDepartmentName() ));
sb.append(String.format("<td>%s</td>", e.getPositionName() ));
sb.append(String.format("<td>%s</td>", e.getRegionName() ));
sb.append(String.format("<td style = \"text-align : right;\">%,d</td>", e.getBasicPay() ));
sb.append(String.format("<td style = \"text-align : right;\">%,d</td>", e.getExtraPay() ));
sb.append(String.format("<td style = \"text-align : right;\">%,d</td>", e.getPay() ));
sb.append(String.format("<td><input type = \"button\" value = \"삭제\" class = \"btnDelete\"></td>"));
sb.append(String.format("</tr>\r\n"));
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>직원관리(JSP버전)</title>
<link rel="stylesheet" type="text/css" href="TableStyle.css">
<link rel="stylesheet" type="text/css" href="DivStyle.css">
<!-- 문제) jQuery를 이용해서 버튼에 대한 화면 전환 액션 추가 -->
</head>
<body>
<div>
<%--메뉴 영역--%>
<div class = "title">
<%--
동일한 메뉴 디자인을 여러 페이지에 적용한 경우
수정 사항이 발생하면 모든 페이지를 동일하게 수정해야 한다.
-> 동일한 메뉴 디자인을 별도의 페이지로 작성
-> 필요하는 페이지에 동적 삽입
--%>
<h1>직원관리 (JSP버전)</h1>
<c:import url="EmployeeMenu.jsp"></c:import>
</div>
<%--콘텐츠 영역--%>
<div class = "main">
<h2>[직원명단]</h2>
<form>
<input type = "button" value = "직원추가" id = "btnAdd" name = "btnAdd">
<input type = "button" value = "직원검색" id = "btnSearch" name = "btnSearch" onclick="location.href='EmployeeSearch.jsp'">
</form>
<!-- <p>직원수 : 1명</p> -->
<p>직원수 : <%=count%> 명</p>
<table id ="t01" style = "font-size:10pt;">
<tr>
<th>직원번호</th><th>이름</th><th>생년월일</th><th>양음력</th><th>전화번호</th>
<th>부서명</th><th>직위명</th><th>지역명</th><th>기본급</th><th>수당</th><th>급여</th><th>삭제</th>
</tr>
<%-- <tr>
<td>1</td><td>홍길동</td><td>1991-03-01</td><td>양력</td><td>010-1234-1234</td>
<td>개발부</td><td>사원</td><td>서울</td>
<td style = "text-align: right;">1,000,000</td>
<td style = "text-align: right;">500,000</td>
<td style = "text-align: right;">1,500,000</td>
id ="" 식별자 사용 불가 ->반복문을 사용하기 떄문에
중복이 가능한 식별자 class =""를 사용한다.
<td><input type = "button" value = "삭제" class = "btnDelete"></td>
</tr> --%>
<%= sb.toString()%>
</table>
</div>
</div>
</body>
</html>
------------------------------------------