----------------------------
직원관리 Servlet(MVC 패턴) 방식
- 서블릿 주소를 확장자 형태 사용.
- web.xml 파일에는 확장자 형태의 주소 한 개만 등록
- 주소 분석 및 액션 요청을 위한 전용 서블릿 클래스 작성.
- 액션 담당 전용 클래스 작성.

** 환경 설정 추가 -> WEB-INF/source 폴더 하위에 JSP 페이지 등록

10. 소스코드 -> 로그인, 관리자, 직원 전용 페이지


//Controller.java
package com.test;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.*;
import com.sun.corba.se.spi.orbutil.fsm.*;

public class Controller extends HttpServlet {

 private static final long serialVersionUID = 1L;

 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  doGetPost(req, resp);
 }

 @Override
 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  doGetPost(req, resp);
 }

 private void doGetPost(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {

  // 요청 주소 분석 및 액션 메소드 호출
  String uri = request.getRequestURI();
  // -> "http://localhost:8090/프로젝트이름/Sample.it"

  Action action = new Action();
  String result = "Error.jsp";

  //요청 주소별로 작성할 것.
  if (uri.indexOf("RegionList.it") != -1) {
   // 액션 메소드 호출
   // 메소드 결과는 URI 주소 형태를 가지고 있다.
   result = action.regionList(request, response);
  }
  
  if (uri.indexOf("RegionInsert.it") != -1) {
   result = action.regionInsert(request, response);
  }
  
  if (uri.indexOf("RegionDelete.it") != -1) {
   result = action.regionDelete(request, response);
  }
  
  if (uri.indexOf("RegionUpdate.it") != -1) {
   result = action.regionUpdate(request, response);
  }
  
  if (uri.indexOf("PositionList.it") != -1) {
   // 액션 메소드 호출
   // 메소드 결과는 URI 주소 형태를 가지고 있다.
   result = action.positionList(request, response);
  }
  
  if (uri.indexOf("PositionInsert.it") != -1) {
   result = action.positionInsert(request, response);
  }
  
  if (uri.indexOf("PositionDelete.it") != -1) {
   result = action.positionDelete(request, response);
  }
  
  if (uri.indexOf("PositionUpdate.it") != -1) {
   result = action.positionUpdate(request, response);
  }
  
  if (uri.indexOf("DepartmentList.it") != -1) {
   // 액션 메소드 호출
   // 메소드 결과는 URI 주소 형태를 가지고 있다.
   result = action.departmentList(request, response);
  }
  
  if (uri.indexOf("DepartmentInsert.it") != -1) {
   result = action.departmentInsert(request, response);
  }
  
  if (uri.indexOf("DepartmentDelete.it") != -1) {
   result = action.departmentDelete(request, response);
  }
  
  if (uri.indexOf("DepartmentUpdate.it") != -1) {
   result = action.departmentUpdate(request, response);
  }
  
  
  //문제) 주소 등록
  if (uri.indexOf("EmployeeList.it") != -1) {
   result = action.employeeList(request, response);
  }
  if (uri.indexOf("EmployeeSearch.it") != -1) {
   result = action.employeeSearch(request, response);
  }
  if (uri.indexOf("EmployeeInsertForm.it") != -1) {
   result = action.employeeInsertForm(request, response);
  }
  if (uri.indexOf("EmployeeInsert.it") != -1) {
   result = action.employeeInsert(request, response);
  }
  if (uri.indexOf("PositionReceive.it") != -1) {
   result = action.positionReceive(request, response);
  }
  if (uri.indexOf("EmployeeDelete.it") != -1) {
   result = action.employeeDelete(request, response);
  }
  if (uri.indexOf("EmployeeUpdateForm.it") != -1) {
   result = action.employeeUpdateForm(request, response);
  }
  if (uri.indexOf("EmployeeUpdate.it") != -1) {
   result = action.employeeUpdate(request, response);
  }
  
  
  if (uri.indexOf("LoginForm.it") != -1) {
   result = action.loginForm(request, response);
  }
  if (uri.indexOf("Login.it") != -1) {
   result = action.login(request, response);
  }
  if (uri.indexOf("Logout.it") != -1) {
   result = action.logout(request, response);
  }
  if (uri.indexOf("LogoutForm.it") != -1) {
   result = action.logoutForm(request, response);
  }
  if (uri.indexOf("LoginFail.it") != -1) {
   result = action.loginFail(request, response);
  }
  
  if (uri.indexOf("EmpSearch.it") != -1) {
   result = action.empSearch(request, response);
  }
  
  
  

  // 페이지 전환 -> forward(), sendRedirect() 메소드
  if (result.indexOf("redirect:") != -1) {
   // sendRedirect 요청
   // -> 또 다른 서블릿 주소 요청
   response.sendRedirect(result.substring(9));
  } else {
   // forward 요청
   // -> 연관된 JSP 페이지 요청
   RequestDispatcher dispatcher = request.getRequestDispatcher(result);
   dispatcher.forward(request, response);
  }
 }

}

 

 


//Action.java
package com.test;

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

//액션 전용 클래스 -> 메소드 단위로 액션 처리
public class Action {

 /*
 public String 메소드이름(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
  HttpSession session = request.getSession();

  
  return "WEB-INF/source/요청주소";
  //return "redirect:요청주소";
 }
 */
 
 public String regionList(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  HttpSession session = request.getSession();

 
  //액션 및 결과 출력
  RegionDAO dao = new RegionDAO();
  request.setAttribute("list", dao.regionList());
  
  return "WEB-INF/source/RegionList.jsp";
 }
 
 public String regionInsert(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  HttpSession session = request.getSession();

  //액션 전용
  //데이터 수신(한글 인코딩 추가)
  request.setCharacterEncoding("UTF-8");
  String regionName = request.getParameter("regionName");

  //데이터베이스 액션 -> add() 메소드 호출로 대체
  RegionDAO dao = new RegionDAO();
  Region r = new Region();
  r.setRegionName(regionName);
  dao.add(r);
  return "redirect:RegionList.it";
 }
 
 public String regionDelete(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  HttpSession session = request.getSession();

  //액션 전용
  //데이터 수신(한글 인코딩 추가)
  request.setCharacterEncoding("UTF-8");
  String regionId = request.getParameter("regionId");

  //데이터베이스 액션 -> add() 메소드 호출로 대체
  RegionDAO dao = new RegionDAO();
  dao.remove(regionId);
  
  return "redirect:RegionList.it";
 }
 
 public String regionUpdate(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  HttpSession session = request.getSession();

  //액션 전용
  //데이터 수신(한글 인코딩 추가)
  request.setCharacterEncoding("UTF-8");
  String regionName = request.getParameter("regionName");
  String regionId = request.getParameter("regionId");
  
  //데이터베이스 액션 -> add() 메소드 호출로 대체
  RegionDAO dao = new RegionDAO();
  Region r = new Region();
  r.setRegionName(regionName);
  r.setRegionId(regionId);
  dao.modify(r);
  
  return "redirect:RegionList.it";
 }

 public String positionList(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  HttpSession session = request.getSession();

  //액션 및 결과 출력
  PositionDAO dao = new PositionDAO();
  request.setAttribute("list", dao.positionList());
  
  return "WEB-INF/source/PositionList.jsp";
 }
 
 public String positionInsert(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  HttpSession session = request.getSession();

  //액션 전용
  //데이터 수신(한글 인코딩 추가)
  request.setCharacterEncoding("UTF-8");
  String positionName = request.getParameter("positionName");
  String minBasicPay = request.getParameter("minBasicPay");
  //데이터베이스 액션 -> add() 메소드 호출로 대체
  PositionDAO dao = new PositionDAO();
  Position p = new Position();
  p.setPositionName(positionName);
  p.setMinBasicPay(Integer.parseInt(minBasicPay));
  dao.add(p);
  return "redirect:PositionList.it";
 }
 
 public String positionDelete(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  HttpSession session = request.getSession();

  //액션 전용
  //데이터 수신(한글 인코딩 추가)
  request.setCharacterEncoding("UTF-8");
  String positionId = request.getParameter("positionId");

  //데이터베이스 액션 -> add() 메소드 호출로 대체
  PositionDAO dao = new PositionDAO();
  dao.remove(positionId);
  
  return "redirect:PositionList.it";
 }
 
 public String positionUpdate(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  HttpSession session = request.getSession();

  //액션 전용
  //데이터 수신(한글 인코딩 추가)
  request.setCharacterEncoding("UTF-8");
  String positionName = request.getParameter("positionName");
  String positionId = request.getParameter("positionId");
  String minBasicPay = request.getParameter("minBasicPay");
  //데이터베이스 액션 -> add() 메소드 호출로 대체
  PositionDAO dao = new PositionDAO();
  Position p = new Position();
  p.setPositionName(positionName);
  p.setPositionId(positionId);
  p.setMinBasicPay(Integer.parseInt(minBasicPay));
  dao.modify(p);
  
  return "redirect:PositionList.it";
 }

 public String departmentList(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  HttpSession session = request.getSession();

  //액션 및 결과 출력
  DepartmentDAO dao = new DepartmentDAO();
  request.setAttribute("list", dao.departmentList());
  
  return "WEB-INF/source/DepartmentList.jsp";
 }
 
 public String departmentInsert(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  HttpSession session = request.getSession();

  //액션 전용
  //데이터 수신(한글 인코딩 추가)
  request.setCharacterEncoding("UTF-8");
  String departmentName = request.getParameter("departmentName");

  //데이터베이스 액션 -> add() 메소드 호출로 대체
  DepartmentDAO dao = new DepartmentDAO();
  Department d = new Department();
  d.setDepartmentName(departmentName);
  dao.add(d);
  return "redirect:DepartmentList.it";
 }
 
 public String departmentDelete(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  HttpSession session = request.getSession();

  //액션 전용
  //데이터 수신(한글 인코딩 추가)
  request.setCharacterEncoding("UTF-8");
  String departmentId = request.getParameter("departmentId");

  //데이터베이스 액션 -> add() 메소드 호출로 대체
  DepartmentDAO dao = new DepartmentDAO();
  dao.remove(departmentId);
  
  return "redirect:DepartmentList.it";
 }
 
 public String departmentUpdate(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  HttpSession session = request.getSession();

  //액션 전용
  //데이터 수신(한글 인코딩 추가)
  request.setCharacterEncoding("UTF-8");
  String departmentName = request.getParameter("departmentName");
  String departmentId = request.getParameter("departmentId");
  
  //데이터베이스 액션 -> add() 메소드 호출로 대체
  DepartmentDAO dao = new DepartmentDAO();
  Department d = new Department();
  d.setDepartmentName(departmentName);
  d.setDepartmentId(departmentId);
  dao.modify(d);
  
  return "redirect:DepartmentList.it";
 }
 
 
 
 public String employeeList(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
 
  HttpSession session = request.getSession();

  //문제) 데이터베이스 액션 및 결과 데이터 전달
  EmployeeDAO dao = new EmployeeDAO();
  request.setAttribute("count", dao.count());
  request.setAttribute("list", dao.list());
  
  return "WEB-INF/source/EmployeeList.jsp";
 }
 
 public String employeeSearch(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
 
  HttpSession session = request.getSession();

  //문제) 데이터 수신 및 데이터베이스 액션, 결과 데이터 전달
  request.setCharacterEncoding("UTF-8");
  String searchKey = request.getParameter("searchKey");
  String searchValue = request.getParameter("searchValue");
  if (searchKey != null) {
   EmployeeDAO dao = new EmployeeDAO();
   request.setAttribute("count", dao.count(searchKey, searchValue));
   request.setAttribute("list", dao.list(searchKey, searchValue));
  }
  
  request.setAttribute("searchKey", searchKey);
  request.setAttribute("searchValue", searchValue);
  
  return "WEB-INF/source/EmployeeSearch.jsp";
 }
 
 
 
 public String employeeInsertForm(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  HttpSession session = request.getSession();

  EmployeeDAO dao = new EmployeeDAO();
  
  request.setAttribute("positionList", dao.positionList());
  request.setAttribute("regionList", dao.regionList());
  request.setAttribute("departmentList", dao.departmentList());
  
  return "WEB-INF/source/EmployeeInsertForm.jsp";
 }
 
 public String employeeInsert(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  HttpSession session = request.getSession();

  //데이터 수신
  request.setCharacterEncoding("UTF-8");
  String name = request.getParameter("name");
  String ssn = request.getParameter("ssn");
  String birthday = request.getParameter("birthday");
  String lunar = request.getParameter("lunar");
  String telephone = request.getParameter("telephone");
  String regionId = request.getParameter("regionId");
  String departmentId = request.getParameter("departmentId");
  String positionId = request.getParameter("positionId");
  String basicPay = request.getParameter("basicPay");
  String extraPay = request.getParameter("extraPay");

  //데이터베이스 액션 -> add() 메소드 호출
  EmployeeDAO dao = new EmployeeDAO();
  Employee e = new Employee();
  e.setName(name);
  e.setSsn(ssn);
  e.setBirthday(birthday);
  e.setLunar(Integer.parseInt(lunar));
  e.setTelephone(telephone);
  e.setRegionId(regionId);
  e.setDepartmentId(departmentId);
  e.setPositionId(positionId);
  e.setBasicPay(Integer.parseInt(basicPay));
  e.setExtraPay(Integer.parseInt(extraPay));
  dao.add(e);
  
  return "redirect:EmployeeList.it";
 }
 
 public String positionReceive(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  HttpSession session = request.getSession();

  //페이지 차단 액션 추가 (관리자 전용 페이지)

  
  //데이터 수신 (positionId)
  String positionId = request.getParameter("positionId");

  EmployeeDAO dao = new EmployeeDAO();
  request.setAttribute("result", String.valueOf(dao.getMinBasicPay(positionId)));
  
  return "WEB-INF/source/PositionReceive.jsp";
 }
 
 
 public String employeeDelete(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
   
  HttpSession session = request.getSession();
  
  //페이지 차단 액션 추가 (관리자 전용 페이지)

  
  request.setCharacterEncoding("UTF-8");
  String employeeId = request.getParameter("employeeId");

  EmployeeDAO dao = new EmployeeDAO();
  dao.remove(employeeId);
 
  
  return "redirect:EmployeeList.it";
 }
 
 public String employeeUpdateForm(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  HttpSession session = request.getSession();

  //페이지 차단 액션 추가 (관리자 전용 페이지)

  //데이터 수신 -> emploeeId
  //데이터베이스 액션 -> list("employeeId",value) 메소드

  EmployeeDAO dao = new EmployeeDAO();
  
  String employeeId = request.getParameter("employeeId");
  
  request.setAttribute("emp", (dao.list("0", employeeId)).get(0));
  
  request.setAttribute("positionList", dao.positionList());
  request.setAttribute("departmentList",dao.departmentList());
  request.setAttribute("regionList",dao.regionList());
  
  return "WEB-INF/source/EmployeeUpdateForm.jsp";
 }
 public String employeeUpdate(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  HttpSession session = request.getSession();

  //페이지 차단 액션 추가 (관리자 전용 페이지)
  
  request.setCharacterEncoding("UTF-8");
  
  //데이터 수신
  String employeeId = request.getParameter("employeeId");
  String name = request.getParameter("name");
  String ssn = request.getParameter("ssn");
  String birthday = request.getParameter("birthday");
  String lunar = request.getParameter("lunar");
  String telephone = request.getParameter("telephone");
  String regionId = request.getParameter("regionId");
  String departmentId = request.getParameter("departmentId");
  String positionId = request.getParameter("positionId");
  String basicPay = request.getParameter("minBasicPay");
  String extraPay = request.getParameter("extraPay");
  String grade = request.getParameter("grade");
  
  //DB 액션  -> modify() 메소드 호출
  Employee e = new Employee();
  e.setEmployeeId(employeeId);
  e.setName(name);
  e.setSsn(ssn);
  e.setBirthday(birthday);
  e.setLunar(Integer.parseInt(lunar));
  e.setTelephone(telephone);
  e.setRegionId(regionId);
  e.setDepartmentId(departmentId);
  e.setPositionId(positionId);
  e.setBasicPay(Integer.parseInt(basicPay));
  e.setExtraPay(Integer.parseInt(extraPay));
  e.setGrade(Integer.parseInt(grade));

  EmployeeDAO dao = new EmployeeDAO();
  
  dao.modify(e);
  
  return "redirect:EmployeeList.it";
 }
 
 public String loginForm(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  return "WEB-INF/source/LoginForm.jsp";
 }

 public String login(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  HttpSession session = request.getSession();

  //문제)
  //데이터 수신 -> id, pw, grade
  
  //데이터베이스 액션->로그인 검증
  
  //로그인 실패-> LoginFail.it
  //로그인 성공->관리자->EmployeeList.it
  //로그인 성공->일반직원->EmpSearch.it

  return "LoginFail.it";
 }

 public String logout(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  HttpSession session = request.getSession();
  
  //문제)
  //세션 객체 소멸

  
  
  
  return "redirect:LogoutForm.it";
 }

 public String logoutForm(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  return "WEB-INF/source/LogoutForm.jsp";
 }

 public String loginFail(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  return "WEB-INF/source/LoginFail.jsp";
 }

 
 public String empSearch(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  HttpSession session = request.getSession();
  
  //페이지 차단 액션 추가 (일반 직원용 페이지)
  if (session.getAttribute("login") == null) {
   response.sendRedirect("LoginForm.it");
  }
  
  
  //문제)
  //데이터 수신
  //데이터베이스 액션

  return "WEB-INF/source/EmpSearch.jsp";
 }
 
}

 

 


//EmployeeMenu.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  <p>
   [<a href="EmployeeList.it">직원관리</a>]
   [<a href="RegionList.it">지역관리</a>]
   [<a href="DepartmentList.it">부서관리</a>]
   [<a href="PositionList.it">직위관리</a>]
   <!-- 로그인, 로그아웃 관련 메뉴 추가 예정 -->
   [<a href="Logout.it">로그아웃(${sessionScope.login})</a>]
  </p>

 


//EmpMenu.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  <p>
   <!-- 로그인, 로그아웃 관련 메뉴 추가 예정 -->
   [<a href="Logout.it">로그아웃(${sessionScope.login})</a>]
  </p>

 


---------------------------------------

'MVC' 카테고리의 다른 글

07일차_MVC패턴, 직원관리  (0) 2015.06.30
06일차_MVC패턴, 직원관리  (0) 2015.06.30
05일차_MVC패턴, 직원관리  (0) 2015.06.30
04일차_MVC패턴, 회원관리, 성적관리  (0) 2015.06.30
03일차(2)_모델2방식, 성적관리  (0) 2015.06.30
블로그 이미지

알 수 없는 사용자

,

----------------------------
직원관리 Servlet(MVC 패턴) 방식
- 서블릿 주소를 확장자 형태 사용.
- web.xml 파일에는 확장자 형태의 주소 한 개만 등록
- 주소 분석 및 액션 요청을 위한 전용 서블릿 클래스 작성.
- 액션 담당 전용 클래스 작성.

** 환경 설정 추가 -> WEB-INF/source 폴더 하위에 JSP 페이지 등록

10. 소스코드 -> 직원 삭제, 직원 수정 액션

//EmployeeList.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>직원관리(Servlet MVC 버전)</title>

<link rel="stylesheet" type="text/css" href="TableStyle.css">
<link rel="stylesheet" type="text/css" href="DivStyle.css">

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
 $("#btnSearch").click(function() {
  /* 요청주소 지정시 확장자 .it 사용 */
  $(location).attr("href", "EmployeeSearch.it");
 });
 $("#btnAdd").click(function() {
  $(location).attr("href", "EmployeeInsertForm.it");
 });
 
 
 $(".btnDelete").click(function(){
  var text = $(this).parent().parent().find("td:first").text();
  if(confirm(text+ "번 직원을 삭제할까요?")){
   $(location).attr("href","EmployeeDelete.it?employeeId="+text);
  }
 });

 $(".btnUpdate").click(function () {
  
  var employeeId = $(this).parent().parent().find("td:first").text();
  $(location).attr("href","EmployeeUpdateForm.it?employeeId="+employeeId);
 });
});
</script>

</head>
<body>
<div>
 <%--메뉴 영역--%>
 <div class = "title">
  <h1>직원관리</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>
   <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>
   <td>관리자</td>
   id ="" 식별자 사용 불가 ->반복문을 사용하기 떄문에
   중복이 가능한 식별자 class =""를 사용한다.
   <td><input type = "button" value = "삭제" class = "btnDelete"></td>
   <td><input type = "button" value = "수정" class = "btnUpdate"></td>
   </tr>
   --%>
   <c:forEach var="e" items="${list}">
   <tr>
   <td>${e.employeeId}</td>
   <td>${e.name}</td>
   <td>${e.birthday}</td>
   <td>${e.lunarName}</td>
   <td>${e.telephone}</td>
   <td>${e.regionName}</td>
   <td>${e.departmentName}</td>
   <td>${e.positionName}</td>
   <td style="text-align: right;"><fmt:formatNumber value="${e.basicPay}" groupingUsed="true"></fmt:formatNumber></td>
   <td style="text-align: right;"><fmt:formatNumber value="${e.extraPay}" groupingUsed="true"></fmt:formatNumber></td>
   <td style="text-align: right;"><fmt:formatNumber value="${e.pay}" groupingUsed="true"></fmt:formatNumber></td>
   <td>${e.grade==0?"관리자":"일반"}</td>
   <td><input type="button" value="삭제" class="btnDelete"  ${e.grade==0?"disabled=\"disabled\"":""} ></td>
   <td><input type="button" value="수정" class="btnUpdate"></td>
   </tr>   
   </c:forEach>
  </table>
 </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, grade 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"));
    e.setGrade(rs.getInt("grade"));
    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, grade 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;
   case "9":
    sql += "";
    break; // 전체 검색
   }
   sql += " ORDER BY employeeId";
   pstmt = conn.prepareStatement(sql);
   if (!searchKey.equals("9")) {
    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.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"));
    e.setGrade(rs.getInt("grade"));
    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;
   case "9":
    sql += "";
    break; // 전체 검색
   }
   pstmt = conn.prepareStatement(sql);
   if (!searchKey.equals("9")) {
    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 , ? , ?)
   */

  // 문제) 입력 관련 액션 추가
  Connection conn = null;
  PreparedStatement pstmt = null;

  try {
   conn = DBConn.getConnection();
   String sql = String
     .format("INSERT INTO employee (employeeId,name,ssn,birthday ,lunar,telephone,departmentId ,positionId,regionId ,basicPay,extraPay) VALUES (employeeSeq.nextval, ?, encrypt(?, ?) ,? , ? ,? ,? , ?,? , ?, ?)");
   pstmt = conn.prepareStatement(sql);

   pstmt.setString(1, e.getName());
   pstmt.setString(2, e.getSsn());
   pstmt.setString(3, e.getName());
   pstmt.setString(4, e.getBirthday());
   pstmt.setInt(5, e.getLunar());
   pstmt.setString(6, e.getTelephone());
   pstmt.setString(7, e.getDepartmentId());
   pstmt.setString(8, e.getPositionId());
   pstmt.setString(9, e.getRegionId());
   pstmt.setInt(10, e.getBasicPay());
   pstmt.setInt(11, e.getExtraPay());

   result = pstmt.executeUpdate();

  } catch (Exception ex) {
   ex.printStackTrace();
  } finally {
   try {
    if (pstmt != null) {
     pstmt.close();
    }
   } catch (Exception ex) {

   }
   DBConn.close();
  }

  return result;
 }

 // 직위 종류 출력 메소드
 public ArrayList<Position> positionList() {
  ArrayList<Position> result = new ArrayList<Position>();

  // SELECT positionId, positionName, minBasicPay
  // FROM position
  // ORDER BY positionId
  Connection conn = null;
  PreparedStatement pstmt = null;

  try {
   conn = DBConn.getConnection();

   String sql = "SELECT positionId, positionName, minBasicPay FROM position ORDER BY positionId";
   pstmt = conn.prepareStatement(sql);
   ResultSet rs = pstmt.executeQuery();

   while (rs.next()) {
    Position p = new Position();
    p.setPositionId(rs.getString("positionId"));
    p.setPositionName(rs.getString("positionName"));
    p.setMinBasicPay(rs.getInt("minBasicPay"));
    result.add(p);

   }

   rs.close();

  } catch (Exception ex) {
   ex.printStackTrace();
  } finally {
   try {
    if (pstmt != null) {
     pstmt.close();
    }
   } catch (Exception ex) {

   }
   DBConn.close();
  }

  return result;
 }

 // 최소 기본급 검색 메소드
 public int getMinBasicPay(String positionId) {
  int result = 0;

  // SELECT minBasicPay FROM position WHERE positionId=?
  Connection conn = null;
  PreparedStatement pstmt = null;

  try {
   conn = DBConn.getConnection();

   String sql = "SELECT minBasicPay FROM position WHERE positionId=?";
   pstmt = conn.prepareStatement(sql);
   pstmt.setString(1, positionId);

   ResultSet rs = pstmt.executeQuery();

   while (rs.next()) {
    result = rs.getInt("minBasicPay");
   }

   rs.close();

  } catch (Exception ex) {
   ex.printStackTrace();
  } finally {
   try {
    if (pstmt != null) {
     pstmt.close();
    }
   } catch (Exception ex) {

   }
   DBConn.close();
  }

  return result;
 }

 // 지역 종류 출력 메소드
 public ArrayList<Region> regionList() {

  ArrayList<Region> result = new ArrayList<Region>();

  Connection conn = null;
  PreparedStatement pstmt = null;
  try {
   conn = DBConn.getConnection();

   // SELECT regionId, regionName, delCheck
   // FROM regionView
   // ORDER BY regionId;
   String sql = "SELECT regionId, regionName, delCheck FROM regionView ORDER BY regionId";
   pstmt = conn.prepareStatement(sql);
   ResultSet rs = pstmt.executeQuery();
   while (rs.next()) {
    Region r = new Region();
    r.setRegionId(rs.getString("regionId"));
    r.setRegionName(rs.getString("regionName"));
    r.setDelCheck(rs.getInt("delCheck"));
    result.add(r);
   }
   rs.close();

  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   try {
    if (pstmt != null) {
     pstmt.close();
    }
   } catch (Exception e) {
   }

   DBConn.close();
  }

  return result;
 }

 // 부서 종류 출력 메소드
 public ArrayList<Department> departmentList() {

  ArrayList<Department> result = new ArrayList<Department>();

  Connection conn = null;
  PreparedStatement pstat = null;

  try {
   conn = DBConn.getConnection();
   String sql = "SELECT departmentId, departmentName, delCheck FROM departmentView ORDER BY departmentId";
   pstat = conn.prepareStatement(sql);
   ResultSet rs = pstat.executeQuery();
   while (rs.next()) {
    Department d = new Department();
    d.setDepartmentId(rs.getString("departmentId"));
    d.setDepartmentName(rs.getString("departmentName"));
    d.setDelCheck(rs.getInt("delCheck"));
    result.add(d);
   }
   rs.close();
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   try {
    if (pstat != null) {
     pstat.close();
    }
   } catch (Exception e) {
   }
   DBConn.close();
  }
  return result;
 }

 // 로그인 메소드
 // grade 변수에는 0 또는 1 전달될 예정
 // 0->관리자 로그인 시도
 // 1->일반직원 로그인 시도
 public int login(String id, String pw, String grade) {
  int result = 0;

  Connection conn = null;
  PreparedStatement pstmt = null;

  try {
   conn = DBConn.getConnection();
   String sql = String
     .format("SELECT COUNT(*) AS count FROM employeeView WHERE name = ? AND ssn = encrypt(?,?)");
   if (grade.equals("0")) {
    sql += " AND grade=0";
   }

   pstmt = conn.prepareStatement(sql);
   pstmt.setString(1, id);
   pstmt.setString(2, pw);
   pstmt.setString(3, id);

   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 remove(String employeeId) {
  int result = 0;

  Connection conn = null;
  PreparedStatement pstmt = null;
  try {
   conn = DBConn.getConnection();
   String sql = "DELETE FROM employee where employeeId =?";
   pstmt = conn.prepareStatement(sql);

   pstmt.setString(1, employeeId);

   result = pstmt.executeUpdate();

  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   try {
    if (pstmt != null) {
     pstmt.close();
    }
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
  DBConn.close();
  return result;
 }

 // 직원 수정 메소드
 public int modify(Employee e) {
  int result = 0;

  Connection conn = null;
  PreparedStatement pstmt = null;

  try {
   conn = DBConn.getConnection();
   /*
    * --직원 정보 수정 쿼리 UPDATE employee SET birthday=? ,lunar=?
    * ,telephone=? ,departmentId=? ,positionId=? ,regionId=?
    * ,basicPay=? ,extraPay=? ,grade=0 WHERE employeeId=1 and
    * ssn=encrypt('8012121122345', '홍길동');
    */
   String sql = "UPDATE employee SET birthday=?,lunar=?,telephone=?,departmentId=?,positionId=?,regionId=?,basicPay=?,extraPay=?,grade=? WHERE employeeId=? and ssn=encrypt(?, ?)";
   pstmt = conn.prepareStatement(sql);

   pstmt.setString(1, e.getBirthday());
   pstmt.setInt(2, e.getLunar());
   pstmt.setString(3, e.getTelephone());
   pstmt.setString(4, e.getDepartmentId());
   pstmt.setString(5, e.getPositionId());
   pstmt.setString(6, e.getRegionId());
   pstmt.setInt(7, e.getBasicPay());
   pstmt.setInt(8, e.getExtraPay());
   pstmt.setInt(9, e.getGrade());
   pstmt.setString(10, e.getEmployeeId());
   pstmt.setString(11, e.getSsn());
   pstmt.setString(12, e.getName());

   result = pstmt.executeUpdate();

  } catch (Exception e1) {
   e1.printStackTrace();
  } finally {
   try {
    if (pstmt != null) {
     pstmt.close();
    }
   } catch (Exception e2) {
    e2.printStackTrace();
   }
   DBConn.close();
  }

  return result;
 }

}

 

 

 

 

 

//Action.java
package com.test;

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

//액션 전용 클래스 -> 메소드 단위로 액션 처리
public class Action {

 /*
 public String 메소드이름(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
  
  return "WEB-INF/source/요청주소";
  //return "redirect:요청주소";
 }
 */
 
 public String regionList(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //액션 및 결과 출력
  RegionDAO dao = new RegionDAO();
  request.setAttribute("list", dao.regionList());
  
  return "WEB-INF/source/RegionList.jsp";
 }
 
 public String regionInsert(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //액션 전용
  //데이터 수신(한글 인코딩 추가)
  request.setCharacterEncoding("UTF-8");
  String regionName = request.getParameter("regionName");

  //데이터베이스 액션 -> add() 메소드 호출로 대체
  RegionDAO dao = new RegionDAO();
  Region r = new Region();
  r.setRegionName(regionName);
  dao.add(r);
  return "redirect:RegionList.it";
 }
 
 public String regionDelete(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //액션 전용
  //데이터 수신(한글 인코딩 추가)
  request.setCharacterEncoding("UTF-8");
  String regionId = request.getParameter("regionId");

  //데이터베이스 액션 -> add() 메소드 호출로 대체
  RegionDAO dao = new RegionDAO();
  dao.remove(regionId);
  
  return "redirect:RegionList.it";
 }
 
 public String regionUpdate(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //액션 전용
  //데이터 수신(한글 인코딩 추가)
  request.setCharacterEncoding("UTF-8");
  String regionName = request.getParameter("regionName");
  String regionId = request.getParameter("regionId");
  
  //데이터베이스 액션 -> add() 메소드 호출로 대체
  RegionDAO dao = new RegionDAO();
  Region r = new Region();
  r.setRegionName(regionName);
  r.setRegionId(regionId);
  dao.modify(r);
  
  return "redirect:RegionList.it";
 }

 public String positionList(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //액션 및 결과 출력
  PositionDAO dao = new PositionDAO();
  request.setAttribute("list", dao.positionList());
  
  return "WEB-INF/source/PositionList.jsp";
 }
 
 public String positionInsert(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //액션 전용
  //데이터 수신(한글 인코딩 추가)
  request.setCharacterEncoding("UTF-8");
  String positionName = request.getParameter("positionName");
  String minBasicPay = request.getParameter("minBasicPay");
  //데이터베이스 액션 -> add() 메소드 호출로 대체
  PositionDAO dao = new PositionDAO();
  Position p = new Position();
  p.setPositionName(positionName);
  p.setMinBasicPay(Integer.parseInt(minBasicPay));
  dao.add(p);
  return "redirect:PositionList.it";
 }
 
 public String positionDelete(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //액션 전용
  //데이터 수신(한글 인코딩 추가)
  request.setCharacterEncoding("UTF-8");
  String positionId = request.getParameter("positionId");

  //데이터베이스 액션 -> add() 메소드 호출로 대체
  PositionDAO dao = new PositionDAO();
  dao.remove(positionId);
  
  return "redirect:PositionList.it";
 }
 
 public String positionUpdate(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //액션 전용
  //데이터 수신(한글 인코딩 추가)
  request.setCharacterEncoding("UTF-8");
  String positionName = request.getParameter("positionName");
  String positionId = request.getParameter("positionId");
  String minBasicPay = request.getParameter("minBasicPay");
  //데이터베이스 액션 -> add() 메소드 호출로 대체
  PositionDAO dao = new PositionDAO();
  Position p = new Position();
  p.setPositionName(positionName);
  p.setPositionId(positionId);
  p.setMinBasicPay(Integer.parseInt(minBasicPay));
  dao.modify(p);
  
  return "redirect:PositionList.it";
 }

 public String departmentList(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //액션 및 결과 출력
  DepartmentDAO dao = new DepartmentDAO();
  request.setAttribute("list", dao.departmentList());
  
  return "WEB-INF/source/DepartmentList.jsp";
 }
 
 public String departmentInsert(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //액션 전용
  //데이터 수신(한글 인코딩 추가)
  request.setCharacterEncoding("UTF-8");
  String departmentName = request.getParameter("departmentName");

  //데이터베이스 액션 -> add() 메소드 호출로 대체
  DepartmentDAO dao = new DepartmentDAO();
  Department d = new Department();
  d.setDepartmentName(departmentName);
  dao.add(d);
  return "redirect:DepartmentList.it";
 }
 
 public String departmentDelete(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //액션 전용
  //데이터 수신(한글 인코딩 추가)
  request.setCharacterEncoding("UTF-8");
  String departmentId = request.getParameter("departmentId");

  //데이터베이스 액션 -> add() 메소드 호출로 대체
  DepartmentDAO dao = new DepartmentDAO();
  dao.remove(departmentId);
  
  return "redirect:DepartmentList.it";
 }
 
 public String departmentUpdate(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //액션 전용
  //데이터 수신(한글 인코딩 추가)
  request.setCharacterEncoding("UTF-8");
  String departmentName = request.getParameter("departmentName");
  String departmentId = request.getParameter("departmentId");
  
  //데이터베이스 액션 -> add() 메소드 호출로 대체
  DepartmentDAO dao = new DepartmentDAO();
  Department d = new Department();
  d.setDepartmentName(departmentName);
  d.setDepartmentId(departmentId);
  dao.modify(d);
  
  return "redirect:DepartmentList.it";
 }
 
 
 
 public String employeeList(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
 
  //문제) 데이터베이스 액션 및 결과 데이터 전달
  EmployeeDAO dao = new EmployeeDAO();
  request.setAttribute("count", dao.count());
  request.setAttribute("list", dao.list());
  
  return "WEB-INF/source/EmployeeList.jsp";
 }
 
 public String employeeSearch(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
 
  //문제) 데이터 수신 및 데이터베이스 액션, 결과 데이터 전달
  request.setCharacterEncoding("UTF-8");
  String searchKey = request.getParameter("searchKey");
  String searchValue = request.getParameter("searchValue");
  if (searchKey != null) {
   EmployeeDAO dao = new EmployeeDAO();
   request.setAttribute("count", dao.count(searchKey, searchValue));
   request.setAttribute("list", dao.list(searchKey, searchValue));
  }
  
  request.setAttribute("searchKey", searchKey);
  request.setAttribute("searchValue", searchValue);
  
  return "WEB-INF/source/EmployeeSearch.jsp";
 }
 
 
 
 public String employeeInsertForm(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  EmployeeDAO dao = new EmployeeDAO();
  
  request.setAttribute("positionList", dao.positionList());
  request.setAttribute("regionList", dao.regionList());
  request.setAttribute("departmentList", dao.departmentList());
  
  return "WEB-INF/source/EmployeeInsertForm.jsp";
 }
 
 public String employeeInsert(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  //데이터 수신
  request.setCharacterEncoding("UTF-8");
  String name = request.getParameter("name");
  String ssn = request.getParameter("ssn");
  String birthday = request.getParameter("birthday");
  String lunar = request.getParameter("lunar");
  String telephone = request.getParameter("telephone");
  String regionId = request.getParameter("regionId");
  String departmentId = request.getParameter("departmentId");
  String positionId = request.getParameter("positionId");
  String basicPay = request.getParameter("basicPay");
  String extraPay = request.getParameter("extraPay");

  //데이터베이스 액션 -> add() 메소드 호출
  EmployeeDAO dao = new EmployeeDAO();
  Employee e = new Employee();
  e.setName(name);
  e.setSsn(ssn);
  e.setBirthday(birthday);
  e.setLunar(Integer.parseInt(lunar));
  e.setTelephone(telephone);
  e.setRegionId(regionId);
  e.setDepartmentId(departmentId);
  e.setPositionId(positionId);
  e.setBasicPay(Integer.parseInt(basicPay));
  e.setExtraPay(Integer.parseInt(extraPay));
  dao.add(e);
  
  return "redirect:EmployeeList.it";
 }
 
 public String positionReceive(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  //데이터 수신 (positionId)
  String positionId = request.getParameter("positionId");

  EmployeeDAO dao = new EmployeeDAO();
  request.setAttribute("result", String.valueOf(dao.getMinBasicPay(positionId)));
  
  return "WEB-INF/source/PositionReceive.jsp";
 }
 
 
 public String employeeDelete(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
   
   request.setCharacterEncoding("UTF-8");
   String employeeId = request.getParameter("employeeId");

   EmployeeDAO dao = new EmployeeDAO();
   dao.remove(employeeId);
  
   
   return "redirect:EmployeeList.it";
 }
 
 public String employeeUpdateForm(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  //데이터 수신 -> emploeeId
  //데이터베이스 액션 -> list("employeeId",value) 메소드

  EmployeeDAO dao = new EmployeeDAO();
  
  String employeeId = request.getParameter("employeeId");
  
  request.setAttribute("emp", (dao.list("0", employeeId)).get(0));
  
  request.setAttribute("positionList", dao.positionList());
  request.setAttribute("departmentList",dao.departmentList());
  request.setAttribute("regionList",dao.regionList());
  
  return "WEB-INF/source/EmployeeUpdateForm.jsp";
 }
 public String employeeUpdate(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  
  request.setCharacterEncoding("UTF-8");
  
  //데이터 수신
  String employeeId = request.getParameter("employeeId");
  String name = request.getParameter("name");
  String ssn = request.getParameter("ssn");
  String birthday = request.getParameter("birthday");
  String lunar = request.getParameter("lunar");
  String telephone = request.getParameter("telephone");
  String regionId = request.getParameter("regionId");
  String departmentId = request.getParameter("departmentId");
  String positionId = request.getParameter("positionId");
  String basicPay = request.getParameter("minBasicPay");
  String extraPay = request.getParameter("extraPay");
  String grade = request.getParameter("grade");
  
  //DB 액션  -> modify() 메소드 호출
  Employee e = new Employee();
  e.setEmployeeId(employeeId);
  e.setName(name);
  e.setSsn(ssn);
  e.setBirthday(birthday);
  e.setLunar(Integer.parseInt(lunar));
  e.setTelephone(telephone);
  e.setRegionId(regionId);
  e.setDepartmentId(departmentId);
  e.setPositionId(positionId);
  e.setBasicPay(Integer.parseInt(basicPay));
  e.setExtraPay(Integer.parseInt(extraPay));
  e.setGrade(Integer.parseInt(grade));

  EmployeeDAO dao = new EmployeeDAO();
  
  dao.modify(e);
  
  return "redirect:EmployeeList.it";
 }
 
 
 
 
 
 
}

 

 


//Controller.java
package com.test;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.*;
import com.sun.corba.se.spi.orbutil.fsm.*;

public class Controller extends HttpServlet {

 private static final long serialVersionUID = 1L;

 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  doGetPost(req, resp);
 }

 @Override
 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  doGetPost(req, resp);
 }

 private void doGetPost(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {

  // 요청 주소 분석 및 액션 메소드 호출
  String uri = request.getRequestURI();
  // -> "http://localhost:8090/프로젝트이름/Sample.it"

  Action action = new Action();
  String result = "Error.jsp";

  //요청 주소별로 작성할 것.
  if (uri.indexOf("RegionList.it") != -1) {
   // 액션 메소드 호출
   // 메소드 결과는 URI 주소 형태를 가지고 있다.
   result = action.regionList(request, response);
  }
  
  if (uri.indexOf("RegionInsert.it") != -1) {
   result = action.regionInsert(request, response);
  }
  
  if (uri.indexOf("RegionDelete.it") != -1) {
   result = action.regionDelete(request, response);
  }
  
  if (uri.indexOf("RegionUpdate.it") != -1) {
   result = action.regionUpdate(request, response);
  }
  
  if (uri.indexOf("PositionList.it") != -1) {
   // 액션 메소드 호출
   // 메소드 결과는 URI 주소 형태를 가지고 있다.
   result = action.positionList(request, response);
  }
  
  if (uri.indexOf("PositionInsert.it") != -1) {
   result = action.positionInsert(request, response);
  }
  
  if (uri.indexOf("PositionDelete.it") != -1) {
   result = action.positionDelete(request, response);
  }
  
  if (uri.indexOf("PositionUpdate.it") != -1) {
   result = action.positionUpdate(request, response);
  }
  
  if (uri.indexOf("DepartmentList.it") != -1) {
   // 액션 메소드 호출
   // 메소드 결과는 URI 주소 형태를 가지고 있다.
   result = action.departmentList(request, response);
  }
  
  if (uri.indexOf("DepartmentInsert.it") != -1) {
   result = action.departmentInsert(request, response);
  }
  
  if (uri.indexOf("DepartmentDelete.it") != -1) {
   result = action.departmentDelete(request, response);
  }
  
  if (uri.indexOf("DepartmentUpdate.it") != -1) {
   result = action.departmentUpdate(request, response);
  }
  
  
  //문제) 주소 등록
  if (uri.indexOf("EmployeeList.it") != -1) {
   result = action.employeeList(request, response);
  }
  if (uri.indexOf("EmployeeSearch.it") != -1) {
   result = action.employeeSearch(request, response);
  }
  if (uri.indexOf("EmployeeInsertForm.it") != -1) {
   result = action.employeeInsertForm(request, response);
  }
  if (uri.indexOf("EmployeeInsert.it") != -1) {
   result = action.employeeInsert(request, response);
  }
  if (uri.indexOf("PositionReceive.it") != -1) {
   result = action.positionReceive(request, response);
  }
  if (uri.indexOf("EmployeeDelete.it") != -1) {
   result = action.employeeDelete(request, response);
  }
  if (uri.indexOf("EmployeeUpdateForm.it") != -1) {
   result = action.employeeUpdateForm(request, response);
  }
  if (uri.indexOf("EmployeeUpdate.it") != -1) {
   result = action.employeeUpdate(request, response);
  }
  
  

  // 페이지 전환 -> forward(), sendRedirect() 메소드
  if (result.indexOf("redirect:") != -1) {
   // sendRedirect 요청
   // -> 또 다른 서블릿 주소 요청
   response.sendRedirect(result.substring(9));
  } else {
   // forward 요청
   // -> 연관된 JSP 페이지 요청
   RequestDispatcher dispatcher = request.getRequestDispatcher(result);
   dispatcher.forward(request, response);
  }
 }

}

 

 

 

 

 


//EmployeeUpdateForm.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>직원관리(Servlet MVC 버전)</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"
 });

 $("#btnSearch").click(function() {
  $(location).attr("href", "EmployeeSearch.it");
 });
 $("#btnList").click(function() {
  $(location).attr("href", "EmployeeList.it");
 });

 //기본급
 minBasicPay($("#positionId").val());
 
 //선택 목록에 체인지 이벤트 등록
 $("#positionId").change(function(){
  minBasicPay($("#positionId").val());
 });
 
 
 //양/음력 자동 선택
 for (var i=0; i<$(".lunar").length; ++i) {
  var lunar = $(".lunar").eq(i);
  if ($(lunar).val() == "${emp.lunar}") {
   $(lunar).attr("checked", "checked");
  }
 }
 
 //지역 자동 선택
 var regionOptions = $("#regionId").find("option");
 for (var i=0; i<$(regionOptions).length; ++i) {
  var regionOption = $(regionOptions).eq(i);
  if ($(regionOption).val() == "${emp.regionId}") {
   $(regionOption).attr("selected", "selected");
  }
 }

 //문제) 자동 선택 과정 추가
 //부서, 직위 항목
 //등급

 var positionOptions = $("#positionId").find("option");
 for (var i = 0; i < $(positionOptions).length; ++i) {
  var positionOption = $(positionOptions).eq(i);
  if ($(positionOption).val() == "${emp.positionId}") {
   $(positionOption).attr("selected", "selected");
  }
 }

 var departmentOptions = $("#departmentId").find("option");
 for (var i = 0; i < $(departmentOptions).length; ++i) {
  var departmentOption = $(departmentOptions).eq(i);
  if ($(departmentOption).val() == "${emp.departmentId}") {
   $(departmentOption).attr("selected", "selected");
  }
 }
 
 var grades = $(".grade");
 for (var i = 0; i < $(grades).length; i++) {
  var grade = $(grades).eq(i);
  if ($(grade).val() == "${emp.grade}") {
   $(grade).attr("checked", "checked");
  }
 }

});

function minBasicPay(positionId) {

 $.get("PositionReceive.it?positionId=" + $("#positionId").val(),
   function(result) {
    $("#minBasicPay").html(result);
   });
}
</script>


</head>
<body>
<div>
 <%--메뉴 영역--%>
 <div class = "title">
 <%--
  동일한 메뉴 디자인을 여러 페이지에 적용한 경우
  수정 사항이 발생하면 모든 페이지를 동일하게 수정해야 한다.
  -> 동일한 메뉴 디자인을 별도의 페이지로 작성
  -> 필요하는 페이지에 동적 삽입
 --%>
  <h1>직원관리</h1>
  <c:import url="EmployeeMenu.jsp"></c:import>
 </div>
 <%--콘텐츠 영역--%>
 <div class = "main">
  <h2>[직원명단]</h2>
  
  <form>
   <%-- 직원명단 버튼은 식별자로 class 사용 --%>
   <input type="button" value="직원명단" id="btnList">
   <input type="button" value="직원검색" id="btnSearch">
  </form>
  
         <form action="EmployeeUpdate.it" method="post" id="myForm">
            <table id="t02">
               <tr>
                  <th>직원번호</th>
                  <td><input type="text" id="employeeId" name="employeeId" readonly="readonly" value="${emp.employeeId}"> readonly</td>
               </tr>
               <tr>
                  <th>이름</th>
                  <td><input type="text" id="name" name="name" readonly="readonly" value="${emp.name}"> readonly</td>
               </tr>
               <tr>
                  <th>주민번호</th>
                  <td><input type="text" id="ssn" name="ssn" required="required"> 재입력 </td>
               </tr>
               <tr>
                  <th>생년월일</th>
                  <td>
                  <!-- required="required" HTML5 전용 -->
                  <input type="text" id="birthday" name="birthday" value="${emp.birthday}" required="required">달력
                 
                  </td>
               </tr>
               <tr>
                  <th>양/음력</th>
                  <td><input type="radio" class="lunar" name="lunar" value="0" >양력
                     <input type="radio" class="lunar" name="lunar" value="1">음력</td>
               </tr>
               <tr>
                  <th>전화번호</th>
                  <td><input type="text" id="telephone" name="telephone" value="${emp.telephone }" required="required"></td>
               </tr>
               <tr>
                  <th>지역명</th>
                  <td><select id="regionId" name="regionId">
                        <!-- <option value="1">서울</option> -->
                        <c:forEach var="r" items="${regionList}">
                        <option value="${r.regionId}">${r.regionName}</option>
                        </c:forEach>
                  </select></td>
               </tr>
               <tr>
                  <th>부서명</th>
                  <td><select id="departmentId" name="departmentId">
                        <!-- <option value="1">개발부</option> -->
                        <c:forEach var="d" items="${departmentList}">
                        <option value="${d.departmentId}">${d.departmentName}</option>
                        </c:forEach>
                  </select></td>
               </tr>
               <tr>
                  <th>직위명</th>
                  <td><select id="positionId" name="positionId">
                        <!-- <select><option>사원</option></select> -->
                                <c:forEach var="p" items="${positionList}">
                        <option value="${p.positionId}">${p.positionName}</option>
                        </c:forEach>

                  </select></td>
               </tr>
               <tr>
                  <th>기본급</th>
                  <td><input type="text" name="minBasicPay" value="${emp.basicPay }" required="required">(최소 <span id="minBasicPay"></span>원
                     이상)</td>
               </tr>
               <tr>
                  <th>수당</th>
                  <td><input type="text" name="extraPay" value="${emp.extraPay }"   required="required"></td>
               </tr>
               <tr>
                  <th>등급</th>
                  <td><input type="radio" class="grade" name="grade" value="0" >관리자
                     <input type="radio" class="grade" name="grade" value="1">일반직원</td>
               <tr>
                  <th></th>
                  <td><input type="submit" value="직원수정"></td>
               </tr>
            </table>
         </form>
  
 
 </div>
</div>
</body>
</html>

 

------------------------------------------------

 

 

 

 

 

 


 

 

'MVC' 카테고리의 다른 글

08일차_MVC패턴, 직원관리  (0) 2015.06.30
06일차_MVC패턴, 직원관리  (0) 2015.06.30
05일차_MVC패턴, 직원관리  (0) 2015.06.30
04일차_MVC패턴, 회원관리, 성적관리  (0) 2015.06.30
03일차(2)_모델2방식, 성적관리  (0) 2015.06.30
블로그 이미지

알 수 없는 사용자

,

-----------------------------
직원관리 Servlet(MVC 패턴) 방식
- 서블릿 주소를 확장자 형태 사용.
- web.xml 파일에는 확장자 형태의 주소 한 개만 등록
- 주소 분석 및 액션 요청을 위한 전용 서블릿 클래스 작성.
- 액션 담당 전용 클래스 작성.

** 환경 설정 추가 -> WEB-INF/source 폴더 하위에 JSP 페이지 등록

10. 소스코드


//Employee.java -> grade 항목 추가
package com.test;

public class Employee {

 private String employeeId
 , name
 , ssn
 , birthday
 , lunarName
 , telephone
 , departmentId
 , departmentName
 , positionId
 , positionName
 , regionId
 , regionName;
 
 private int lunar; // 0(양력) 또는 1(음력)
 private int basicPay, extraPay, pay;
 
 private int grade; //등급 (0 또는 1)

 public int getGrade() {
  return grade;
 }
 public void setGrade(int grade) {
  this.grade = grade;
 }

 public String getSsn() {
  return ssn;
 }
 public void setSsn(String ssn) {
  this.ssn = ssn;
 }
 
 public String getEmployeeId() {
  return employeeId;
 }
 public void setEmployeeId(String employeeId) {
  this.employeeId = employeeId;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getBirthday() {
  return birthday;
 }
 public void setBirthday(String birthday) {
  this.birthday = birthday;
 }
 public String getLunarName() {
  return lunarName;
 }
 public void setLunarName(String lunarName) {
  this.lunarName = lunarName;
 }
 public String getTelephone() {
  return telephone;
 }
 public void setTelephone(String telephone) {
  this.telephone = telephone;
 }
 public String getDepartmentId() {
  return departmentId;
 }
 public void setDepartmentId(String departmentId) {
  this.departmentId = departmentId;
 }
 public String getDepartmentName() {
  return departmentName;
 }
 public void setDepartmentName(String departmentName) {
  this.departmentName = departmentName;
 }
 public String getPositionId() {
  return positionId;
 }
 public void setPositionId(String positionId) {
  this.positionId = positionId;
 }
 public String getPositionName() {
  return positionName;
 }
 public void setPositionName(String positionName) {
  this.positionName = positionName;
 }
 public String getRegionId() {
  return regionId;
 }
 public void setRegionId(String regionId) {
  this.regionId = regionId;
 }
 public String getRegionName() {
  return regionName;
 }
 public void setRegionName(String regionName) {
  this.regionName = regionName;
 }
 public int getLunar() {
  return lunar;
 }
 public void setLunar(int lunar) {
  this.lunar = lunar;
 }
 public int getBasicPay() {
  return basicPay;
 }
 public void setBasicPay(int basicPay) {
  this.basicPay = basicPay;
 }
 public int getExtraPay() {
  return extraPay;
 }
 public void setExtraPay(int extraPay) {
  this.extraPay = extraPay;
 }
 public int getPay() {
  return pay;
 }
 public void setPay(int pay) {
  this.pay = pay;
 }
 
}

 

 

//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, grade 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"));
    e.setGrade(rs.getInt("grade"));
    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, grade 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;
   case "9" : sql += ""; break; //전체 검색
   }
   sql += " ORDER BY employeeId";
   pstmt = conn.prepareStatement(sql);
   if (!searchKey.equals("9")) {
    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"));
    e.setGrade(rs.getInt("grade"));
    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;
    case "9" : sql += ""; break; //전체 검색
    }
    pstmt = conn.prepareStatement(sql);
    if (!searchKey.equals("9")) {
     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
   , ?
   , ?)
   */
   
   //문제) 입력 관련 액션 추가
        Connection conn = null;
        PreparedStatement pstmt = null;

        try{
           conn = DBConn.getConnection();
           String sql = String.format("INSERT INTO employee (employeeId,name,ssn,birthday ,lunar,telephone,departmentId ,positionId,regionId ,basicPay,extraPay) VALUES (employeeSeq.nextval, ?, encrypt(?, ?) ,? , ? ,? ,? , ?,? , ?, ?)");
           pstmt = conn.prepareStatement(sql);

           pstmt.setString(1, e.getName());
           pstmt.setString(2, e.getSsn());
           pstmt.setString(3,e.getName());
           pstmt.setString(4, e.getBirthday());
           pstmt.setInt(5, e.getLunar());
           pstmt.setString(6, e.getTelephone());
           pstmt.setString(7, e.getDepartmentId());
           pstmt.setString(8, e.getPositionId());
           pstmt.setString(9, e.getRegionId());
           pstmt.setInt(10, e.getBasicPay());
           pstmt.setInt(11, e.getExtraPay());

           result = pstmt.executeUpdate();

        }catch(Exception ex){
           ex.printStackTrace();
        }finally{
           try{
              if(pstmt != null){
                 pstmt.close();
              }
           }catch(Exception ex){

           }
           DBConn.close();
        }   
   
   
   return result;
  }
  

  //직위 종류 출력 메소드
  public ArrayList<Position> positionList() {
   ArrayList<Position> result = new ArrayList<Position>();
   
   //SELECT positionId, positionName, minBasicPay
      // FROM position
      // ORDER BY positionId
     Connection conn = null;
     PreparedStatement pstmt = null;
   
     try{
        conn = DBConn.getConnection();
   
     String sql = "SELECT positionId, positionName, minBasicPay FROM position ORDER BY positionId";
     pstmt = conn.prepareStatement(sql);
     ResultSet rs = pstmt.executeQuery();
     
     while(rs.next()){
      Position p = new Position();
      p.setPositionId(rs.getString("positionId"));
      p.setPositionName(rs.getString("positionName"));
      p.setMinBasicPay(rs.getInt("minBasicPay"));
      result.add(p);
      
     }
     
     rs.close();
       
     }catch(Exception ex){
            ex.printStackTrace();
         }finally{
            try{
               if(pstmt != null){
                  pstmt.close();
               }
            }catch(Exception ex){
   
            }
            DBConn.close();
     }           
   
   return result;
  }
  
  //최소 기본급 검색 메소드
  public int getMinBasicPay(String positionId) {
   int result = 0;
   
   //SELECT minBasicPay FROM position WHERE positionId=?
     Connection conn = null;
     PreparedStatement pstmt = null;
   
     try{
        conn = DBConn.getConnection();
      
     String sql = "SELECT minBasicPay FROM position WHERE positionId=?";
     pstmt = conn.prepareStatement(sql);
     pstmt.setString(1, positionId);
     
     ResultSet rs = pstmt.executeQuery();
     
     while(rs.next()){
      result = rs.getInt("minBasicPay");
     }
     
     rs.close();

     
     }catch(Exception ex){
            ex.printStackTrace();
         }finally{
            try{
               if(pstmt != null){
                  pstmt.close();
               }
            }catch(Exception ex){
   
            }
            DBConn.close();
     }    
   
   return result;
  }
  
  //지역 종류 출력 메소드
  public ArrayList<Region> regionList() {
   
   ArrayList<Region> result = new ArrayList<Region>();

   Connection conn = null;
   PreparedStatement pstmt = null;
   try {
    conn = DBConn.getConnection(); 
    
    //SELECT regionId, regionName, delCheck
    // FROM regionView
    // ORDER BY regionId;
    String sql = "SELECT regionId, regionName, delCheck FROM regionView ORDER BY regionId";
    pstmt = conn.prepareStatement(sql);
    ResultSet rs = pstmt.executeQuery();
    while(rs.next()) {
     Region r = new Region();
     r.setRegionId(rs.getString("regionId"));
     r.setRegionName(rs.getString("regionName"));
     r.setDelCheck(rs.getInt("delCheck"));
     result.add(r);
    }
    rs.close();
   
   }catch(Exception e){
    e.printStackTrace();
   }finally{
    try {
     if (pstmt != null) {
      pstmt.close();
     }
    }catch(Exception e){
    }
    
    DBConn.close();   
   }   
   
   return result;
  }  
  
  //부서 종류 출력 메소드
  public ArrayList<Department> departmentList() {
   
   ArrayList<Department> result = new ArrayList<Department>();
   
   Connection conn = null;
   PreparedStatement pstat = null;

   try{
    conn = DBConn.getConnection();
    String sql = "SELECT departmentId, departmentName, delCheck FROM departmentView ORDER BY departmentId";
    pstat = conn.prepareStatement(sql);
    ResultSet rs = pstat.executeQuery();
    while(rs.next()){
     Department d = new Department();
     d.setDepartmentId(rs.getString("departmentId"));
     d.setDepartmentName(rs.getString("departmentName"));
     d.setDelCheck(rs.getInt("delCheck"));
     result.add(d);
    }
    rs.close();
   }catch(Exception e){
    e.printStackTrace();
   }finally{
    try{
     if(pstat!=null){
      pstat.close();
     }
    }catch(Exception e){
    }
    DBConn.close();
   }
   return result;
  }  
  
  //로그인 메소드
  //grade 변수에는 0 또는 1 전달될 예정
  //0->관리자 로그인 시도
  //1->일반직원 로그인 시도
  public int login(String id, String pw, String grade){
   int result = 0;
   
   Connection conn = null;
   PreparedStatement pstmt = null;
   
   try{
    conn = DBConn.getConnection();
    String sql = String.format("SELECT COUNT(*) AS count FROM employeeView WHERE name = ? AND ssn = encrypt(?,?)");
    if (grade.equals("0")) {
     sql += " AND grade=0";
    }

    pstmt = conn.prepareStatement(sql);
     pstmt.setString(1, id);
     pstmt.setString(2, pw);
     pstmt.setString(3, id);

    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 remove(String employeeId) {
   int result = 0;
   
   //DELETE FROM employee WHERE employeeId=?
   
   //문제) 삭제 액션 작성
   
   return result;
  }
  
  //직원 수정 메소드
  public int modify(Employee emp) {
   int result = 0;
   /*
   UPDATE employee SET birthday=?
     ,lunar=?
     ,telephone=?
     ,departmentId=?
     ,positionId=?
     ,regionId=?
     ,basicPay=?
     ,extraPay=?
     ,grade=?
    WHERE employeeId=? and ssn=encrypt(?, ?);
    */
   
   //문제) 수정 액션 작성
   
   return result;
  }
   
  
}

 


//Action.java
package com.test;

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

//액션 전용 클래스 -> 메소드 단위로 액션 처리
public class Action {

 /*
 public String 메소드이름(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
  
  return "WEB-INF/source/요청주소";
  //return "redirect:요청주소";
 }
 */
 
 public String regionList(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //액션 및 결과 출력
  RegionDAO dao = new RegionDAO();
  request.setAttribute("list", dao.regionList());
  
  return "WEB-INF/source/RegionList.jsp";
 }
 
 public String regionInsert(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //액션 전용
  //데이터 수신(한글 인코딩 추가)
  request.setCharacterEncoding("UTF-8");
  String regionName = request.getParameter("regionName");

  //데이터베이스 액션 -> add() 메소드 호출로 대체
  RegionDAO dao = new RegionDAO();
  Region r = new Region();
  r.setRegionName(regionName);
  dao.add(r);
  return "redirect:RegionList.it";
 }
 
 public String regionDelete(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //액션 전용
  //데이터 수신(한글 인코딩 추가)
  request.setCharacterEncoding("UTF-8");
  String regionId = request.getParameter("regionId");

  //데이터베이스 액션 -> add() 메소드 호출로 대체
  RegionDAO dao = new RegionDAO();
  dao.remove(regionId);
  
  return "redirect:RegionList.it";
 }
 
 public String regionUpdate(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //액션 전용
  //데이터 수신(한글 인코딩 추가)
  request.setCharacterEncoding("UTF-8");
  String regionName = request.getParameter("regionName");
  String regionId = request.getParameter("regionId");
  
  //데이터베이스 액션 -> add() 메소드 호출로 대체
  RegionDAO dao = new RegionDAO();
  Region r = new Region();
  r.setRegionName(regionName);
  r.setRegionId(regionId);
  dao.modify(r);
  
  return "redirect:RegionList.it";
 }

 public String positionList(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //액션 및 결과 출력
  PositionDAO dao = new PositionDAO();
  request.setAttribute("list", dao.positionList());
  
  return "WEB-INF/source/PositionList.jsp";
 }
 
 public String positionInsert(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //액션 전용
  //데이터 수신(한글 인코딩 추가)
  request.setCharacterEncoding("UTF-8");
  String positionName = request.getParameter("positionName");
  String minBasicPay = request.getParameter("minBasicPay");
  //데이터베이스 액션 -> add() 메소드 호출로 대체
  PositionDAO dao = new PositionDAO();
  Position p = new Position();
  p.setPositionName(positionName);
  p.setMinBasicPay(Integer.parseInt(minBasicPay));
  dao.add(p);
  return "redirect:PositionList.it";
 }
 
 public String positionDelete(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //액션 전용
  //데이터 수신(한글 인코딩 추가)
  request.setCharacterEncoding("UTF-8");
  String positionId = request.getParameter("positionId");

  //데이터베이스 액션 -> add() 메소드 호출로 대체
  PositionDAO dao = new PositionDAO();
  dao.remove(positionId);
  
  return "redirect:PositionList.it";
 }
 
 public String positionUpdate(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //액션 전용
  //데이터 수신(한글 인코딩 추가)
  request.setCharacterEncoding("UTF-8");
  String positionName = request.getParameter("positionName");
  String positionId = request.getParameter("positionId");
  String minBasicPay = request.getParameter("minBasicPay");
  //데이터베이스 액션 -> add() 메소드 호출로 대체
  PositionDAO dao = new PositionDAO();
  Position p = new Position();
  p.setPositionName(positionName);
  p.setPositionId(positionId);
  p.setMinBasicPay(Integer.parseInt(minBasicPay));
  dao.modify(p);
  
  return "redirect:PositionList.it";
 }

 public String departmentList(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //액션 및 결과 출력
  DepartmentDAO dao = new DepartmentDAO();
  request.setAttribute("list", dao.departmentList());
  
  return "WEB-INF/source/DepartmentList.jsp";
 }
 
 public String departmentInsert(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //액션 전용
  //데이터 수신(한글 인코딩 추가)
  request.setCharacterEncoding("UTF-8");
  String departmentName = request.getParameter("departmentName");

  //데이터베이스 액션 -> add() 메소드 호출로 대체
  DepartmentDAO dao = new DepartmentDAO();
  Department d = new Department();
  d.setDepartmentName(departmentName);
  dao.add(d);
  return "redirect:DepartmentList.it";
 }
 
 public String departmentDelete(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //액션 전용
  //데이터 수신(한글 인코딩 추가)
  request.setCharacterEncoding("UTF-8");
  String departmentId = request.getParameter("departmentId");

  //데이터베이스 액션 -> add() 메소드 호출로 대체
  DepartmentDAO dao = new DepartmentDAO();
  dao.remove(departmentId);
  
  return "redirect:DepartmentList.it";
 }
 
 public String departmentUpdate(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //액션 전용
  //데이터 수신(한글 인코딩 추가)
  request.setCharacterEncoding("UTF-8");
  String departmentName = request.getParameter("departmentName");
  String departmentId = request.getParameter("departmentId");
  
  //데이터베이스 액션 -> add() 메소드 호출로 대체
  DepartmentDAO dao = new DepartmentDAO();
  Department d = new Department();
  d.setDepartmentName(departmentName);
  d.setDepartmentId(departmentId);
  dao.modify(d);
  
  return "redirect:DepartmentList.it";
 }
 
 
 
 public String employeeList(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
 
  //문제) 데이터베이스 액션 및 결과 데이터 전달
  EmployeeDAO dao = new EmployeeDAO();
  request.setAttribute("count", dao.count());
  request.setAttribute("list", dao.list());
  
  return "WEB-INF/source/EmployeeList.jsp";
 }
 
 public String employeeSearch(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
 
  //문제) 데이터 수신 및 데이터베이스 액션, 결과 데이터 전달
  request.setCharacterEncoding("UTF-8");
  String searchKey = request.getParameter("searchKey");
  String searchValue = request.getParameter("searchValue");
  if (searchKey != null) {
   EmployeeDAO dao = new EmployeeDAO();
   request.setAttribute("count", dao.count(searchKey, searchValue));
   request.setAttribute("list", dao.list(searchKey, searchValue));
  }
  
  request.setAttribute("searchKey", searchKey);
  request.setAttribute("searchValue", searchValue);
  
  return "WEB-INF/source/EmployeeSearch.jsp";
 }
 
 
 
 public String employeeInsertForm(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  EmployeeDAO dao = new EmployeeDAO();
  
  request.setAttribute("positionList", dao.positionList());
  request.setAttribute("regionList", dao.regionList());
  request.setAttribute("departmentList", dao.departmentList());
  
  return "WEB-INF/source/EmployeeInsertForm.jsp";
 }
 
 public String employeeInsert(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  //데이터 수신
  request.setCharacterEncoding("UTF-8");
  String name = request.getParameter("name");
  String ssn = request.getParameter("ssn");
  String birthday = request.getParameter("birthday");
  String lunar = request.getParameter("lunar");
  String telephone = request.getParameter("telephone");
  String regionId = request.getParameter("regionId");
  String departmentId = request.getParameter("departmentId");
  String positionId = request.getParameter("positionId");
  String basicPay = request.getParameter("basicPay");
  String extraPay = request.getParameter("extraPay");

  //데이터베이스 액션 -> add() 메소드 호출
  EmployeeDAO dao = new EmployeeDAO();
  Employee e = new Employee();
  e.setName(name);
  e.setSsn(ssn);
  e.setBirthday(birthday);
  e.setLunar(Integer.parseInt(lunar));
  e.setTelephone(telephone);
  e.setRegionId(regionId);
  e.setDepartmentId(departmentId);
  e.setPositionId(positionId);
  e.setBasicPay(Integer.parseInt(basicPay));
  e.setExtraPay(Integer.parseInt(extraPay));
  dao.add(e);
  
  return "redirect:EmployeeList.it";
 }
 
 public String positionReceive(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  //데이터 수신 (positionId)
  String positionId = request.getParameter("positionId");

  EmployeeDAO dao = new EmployeeDAO();
  request.setAttribute("result", String.valueOf(dao.getMinBasicPay(positionId)));
  
  return "WEB-INF/source/PositionReceive.jsp";
 }

 
 
}

 

 


//Controller.java
package com.test;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.*;
import com.sun.corba.se.spi.orbutil.fsm.*;

public class Controller extends HttpServlet {

 private static final long serialVersionUID = 1L;

 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  doGetPost(req, resp);
 }

 @Override
 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  doGetPost(req, resp);
 }

 private void doGetPost(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {

  // 요청 주소 분석 및 액션 메소드 호출
  String uri = request.getRequestURI();
  // -> "http://localhost:8090/프로젝트이름/Sample.it"

  Action action = new Action();
  String result = "Error.jsp";

  //요청 주소별로 작성할 것.
  if (uri.indexOf("RegionList.it") != -1) {
   // 액션 메소드 호출
   // 메소드 결과는 URI 주소 형태를 가지고 있다.
   result = action.regionList(request, response);
  }
  
  if (uri.indexOf("RegionInsert.it") != -1) {
   result = action.regionInsert(request, response);
  }
  
  if (uri.indexOf("RegionDelete.it") != -1) {
   result = action.regionDelete(request, response);
  }
  
  if (uri.indexOf("RegionUpdate.it") != -1) {
   result = action.regionUpdate(request, response);
  }
  
  if (uri.indexOf("PositionList.it") != -1) {
   // 액션 메소드 호출
   // 메소드 결과는 URI 주소 형태를 가지고 있다.
   result = action.positionList(request, response);
  }
  
  if (uri.indexOf("PositionInsert.it") != -1) {
   result = action.positionInsert(request, response);
  }
  
  if (uri.indexOf("PositionDelete.it") != -1) {
   result = action.positionDelete(request, response);
  }
  
  if (uri.indexOf("PositionUpdate.it") != -1) {
   result = action.positionUpdate(request, response);
  }
  
  if (uri.indexOf("DepartmentList.it") != -1) {
   // 액션 메소드 호출
   // 메소드 결과는 URI 주소 형태를 가지고 있다.
   result = action.departmentList(request, response);
  }
  
  if (uri.indexOf("DepartmentInsert.it") != -1) {
   result = action.departmentInsert(request, response);
  }
  
  if (uri.indexOf("DepartmentDelete.it") != -1) {
   result = action.departmentDelete(request, response);
  }
  
  if (uri.indexOf("DepartmentUpdate.it") != -1) {
   result = action.departmentUpdate(request, response);
  }
  
  
  //문제) 주소 등록
  if (uri.indexOf("EmployeeList.it") != -1) {
   result = action.employeeList(request, response);
  }
  if (uri.indexOf("EmployeeSearch.it") != -1) {
   result = action.employeeSearch(request, response);
  }
  if (uri.indexOf("EmployeeInsertForm.it") != -1) {
   result = action.employeeInsertForm(request, response);
  }
  if (uri.indexOf("EmployeeInsert.it") != -1) {
   result = action.employeeInsert(request, response);
  }
  if (uri.indexOf("PositionReceive.it") != -1) {
   result = action.positionReceive(request, response);
  }
  
  

  // 페이지 전환 -> forward(), sendRedirect() 메소드
  if (result.indexOf("redirect:") != -1) {
   // sendRedirect 요청
   // -> 또 다른 서블릿 주소 요청
   response.sendRedirect(result.substring(9));
  } else {
   // forward 요청
   // -> 연관된 JSP 페이지 요청
   RequestDispatcher dispatcher = request.getRequestDispatcher(result);
   dispatcher.forward(request, response);
  }
 }

}

 

 

 


//EmployeeList.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>직원관리(Servlet MVC 버전)</title>

<link rel="stylesheet" type="text/css" href="TableStyle.css">
<link rel="stylesheet" type="text/css" href="DivStyle.css">

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
 $("#btnSearch").click(function() {
   /* 요청주소 지정시 확장자 .it 사용 */
   $(location).attr("href", "EmployeeSearch.it");
  });
 $("#btnAdd").click(function() {
  $(location).attr("href", "EmployeeInsertForm.it");
 });
});
</script>

</head>
<body>
<div>
 <%--메뉴 영역--%>
 <div class = "title">
  <h1>직원관리</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>
   <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>
   <td>관리자</td>
   id ="" 식별자 사용 불가 ->반복문을 사용하기 떄문에
   중복이 가능한 식별자 class =""를 사용한다.
   <td><input type = "button" value = "삭제" class = "btnDelete"></td>
   <td><input type = "button" value = "수정" class = "btnUpdate"></td>
   </tr>
   --%>
   <c:forEach var="e" items="${list}">
   <tr>
   <td>${e.employeeId}</td>
   <td>${e.name}</td>
   <td>${e.birthday}</td>
   <td>${e.lunarName}</td>
   <td>${e.telephone}</td>
   <td>${e.departmentName}</td>
   <td>${e.positionName}</td>
   <td>${e.regionName}</td>
   <td style="text-align: right;"><fmt:formatNumber value="${e.basicPay}" groupingUsed="true"></fmt:formatNumber></td>
   <td style="text-align: right;"><fmt:formatNumber value="${e.extraPay}" groupingUsed="true"></fmt:formatNumber></td>
   <td style="text-align: right;"><fmt:formatNumber value="${e.pay}" groupingUsed="true"></fmt:formatNumber></td>
   <td>${e.grade==0?"관리자":"일반"}</td>
   <td><input type="button" value="삭제" class="btnDelete"  ${e.grade==0?"disabled=\"disabled\"":""} ></td>
   <td><input type="button" value="수정" class="btnUpdate"></td>
   </tr>   
   </c:forEach>
  </table>
 </div>
</div>


</body>
</html>

 


//EmployeeSearch.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>직원검색(Servlet MVC 버전)</title>

<link rel="stylesheet" type="text/css" href="TableStyle.css">
<link rel="stylesheet" type="text/css" href="DivStyle.css">

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {
 
 for (var i=0; i<$(".searchKey").length; ++i) {
  var searchKey = $(".searchKey").eq(i);
  if ($(searchKey).val() == "${searchKey}") {
   $(searchKey).attr("checked", "checked");
  }
 }
 
 $("#btnList").click(function() {
   $(location).attr("href", "EmployeeList.it");
  });
 $("#btnAdd").click(function() {
  $(location).attr("href", "EmployeeInsertForm.it");
 });
});


</script>

</head>
<body>
 <div>
  <%--메뉴 영역--%>
  <div class="title">
   <h1>직원관리</h1>
   <c:import url="EmployeeMenu.jsp"></c:import>
  </div>
  <%--콘텐츠 영역--%>
  <div class="main">
   <h2>[직원검색]</h2>
   <form id="t01">
    <input type="button" value="직원명단" id="btnList">
    <input type="button" value="직원추가" id="btnAdd">
   </form>
   <form method="post" id="myForm">
    <p>
     [검색기준]
     <input type="radio" class="searchKey" name="searchKey" value="0" checked="checked">사번
     <input type="radio" class="searchKey" name="searchKey" value="1">주민번호
     <input type="radio" class="searchKey" name="searchKey" value="2">이름
     <input type="radio" class="searchKey" name="searchKey" value="3">지역
     <input type="radio" class="searchKey" name="searchKey" value="4">부서
     <input type="radio" class="searchKey" name="searchKey" value="5">직위
    </p>
    <p>
     검색단어 <input type="text" id="searchValue" name="searchValue" value="${searchValue}">
     <input type="submit" value="직원검색">
    </p>
   </form>
   <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>
     <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>
     <td>관리자</td>
     id ="" 식별자 사용 불가 ->반복문을 사용하기 떄문에
     중복이 가능한 식별자 class =""를 사용한다.
     <td><input type="button" value="삭제" class="btnDelete"></td>
     <td><input type="button" value="수정" class="btnUpdate"></td>
    </tr> --%>
    <c:forEach var="e" items="${list}">
    <tr>
    <td>${e.employeeId}</td>
    <td>${e.name}</td>
    <td>${e.birthday}</td>
    <td>${e.lunarName}</td>
    <td>${e.telephone}</td>
    <td>${e.departmentName}</td>
    <td>${e.positionName}</td>
    <td>${e.regionName}</td>
    <td style="text-align: right;"><fmt:formatNumber value="${e.basicPay}" groupingUsed="true"></fmt:formatNumber></td>
    <td style="text-align: right;"><fmt:formatNumber value="${e.extraPay}" groupingUsed="true"></fmt:formatNumber></td>
    <td style="text-align: right;"><fmt:formatNumber value="${e.pay}" groupingUsed="true"></fmt:formatNumber></td>
    <td>${e.grade==0?"관리자":"일반"}</td>
    <td><input type="button" value="삭제" class="btnDelete"  ${e.grade==0?"disabled=\"disabled\"":""} ></td>
    <td><input type="button" value="수정" class="btnUpdate"></td>
    </tr>   
    </c:forEach>
   </table>
  </div>
 </div>
</body>
</html>

 

 

//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" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>직원관리(Servlet MVC 버전)</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"
 });
 

 $("#btnSearch").click(function() {
  $(location).attr("href", "EmployeeSearch.it");
 });
 $("#btnList").click(function() {
  $(location).attr("href", "EmployeeList.it");
 });

 //기본급
 minBasicPay($("#positionId").val());
 
 //선택 목록에 체인지 이벤트 등록
 $("#positionId").change(function(){
  minBasicPay($("#positionId").val());
 });
});

function minBasicPay(positionId) {
 
 $.get("PositionReceive.it?positionId="+$("#positionId").val(),function(result){
  $("#minBasicPay").html(result);
 });
}

</script>


</head>
<body>
<div>
 <%--메뉴 영역--%>
 <div class = "title">
 <%--
  동일한 메뉴 디자인을 여러 페이지에 적용한 경우
  수정 사항이 발생하면 모든 페이지를 동일하게 수정해야 한다.
  -> 동일한 메뉴 디자인을 별도의 페이지로 작성
  -> 필요하는 페이지에 동적 삽입
 --%>
  <h1>직원관리</h1>
  <c:import url="EmployeeMenu.jsp"></c:import>
 </div>
 <%--콘텐츠 영역--%>
 <div class = "main">
  <h2>[직원명단]</h2>
  
  <form>
   <%-- 직원명단 버튼은 식별자로 class 사용 --%>
   <input type="button" value="직원명단" id="btnList">
   <input type="button" value="직원검색" id="btnSearch">
  </form>
  
   <form action="EmployeeInsert.it" method="post" id="myForm">
    <table id="t02">
     <tr>
      <th>이름</th>
      <td><input type="text" id="name" name="name"></td>
     </tr>
     <tr>
      <th>주민번호</th>
      <td><input type="text" id="ssn" name="ssn"></td>
     </tr>
     <tr>
      <th>생년월일</th>
      <td><input type="text" id="birthday" name="birthday">달력</td>
     </tr>
     <tr>
      <th>양/음력</th>
      <td><input type="radio" class="lunar" name="lunar" value="0" checked="checked">양력
       <input type="radio" class="lunar" name="lunar" value="1">음력</td>
     </tr>
     <tr>
      <th>전화번호</th>
      <td><input type="text" id="telephone" name="telephone"></td>
     </tr>
     <tr>
      <th>지역명</th>
      <td><select id="regionId" name="regionId">
        <!-- <option value="1">서울</option> -->
        <c:forEach var="r" items="${regionList}">
        <option value="${r.regionId}">${r.regionName}</option>
        </c:forEach>
      </select></td>
     </tr>
     <tr>
      <th>부서명</th>
      <td><select id="departmentId" name="departmentId">
        <!-- <option value="1">개발부</option> -->
        <c:forEach var="d" items="${departmentList}">
        <option value="${d.departmentId}">${d.departmentName}</option>
        </c:forEach>
      </select></td>
     </tr>
     <tr>
      <th>직위명</th>
      <td><select id="positionId" name="positionId">
        <!-- <select><option>사원</option></select> -->

        <c:forEach var="p" items="${positionList}">
        <option value="${p.positionId}">${p.positionName}</option>
        </c:forEach>

      </select></td>
     </tr>
     <tr>
      <th>기본급</th>
      <td><input type="text" name="minBasicPay">(최소 <span id="minBasicPay">0</span>원
       이상)</td>
     </tr>
     <tr>
      <th>수당</th>
      <td><input type="text" name="extraPay"></td>
     </tr>
     <tr>
      <th></th>
      <td><input type="submit" value="직원추가"></td>
     </tr>
    </table>
   </form>
 
 </div>
</div>
</body>
</html>

 

 


//PositionReceive.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
${result}

 

 

-----------------------------------------

'MVC' 카테고리의 다른 글

08일차_MVC패턴, 직원관리  (0) 2015.06.30
07일차_MVC패턴, 직원관리  (0) 2015.06.30
05일차_MVC패턴, 직원관리  (0) 2015.06.30
04일차_MVC패턴, 회원관리, 성적관리  (0) 2015.06.30
03일차(2)_모델2방식, 성적관리  (0) 2015.06.30
블로그 이미지

알 수 없는 사용자

,

-----------------------------
직원관리 Servlet(MVC 패턴) 방식
- 서블릿 주소를 확장자 형태 사용.
- web.xml 파일에는 확장자 형태의 주소 한 개만 등록
- 주소 분석 및 액션 요청을 위한 전용 서블릿 클래스 작성.
- 액션 담당 전용 클래스 작성.

** 환경 설정 추가 -> WEB-INF/source 폴더 하위에 JSP 페이지 등록


1. 직원 정보 출력, 입력, 삭제, 수정 기능 구현
- 직원 정보에 대한 입력, 출력, 검색, 삭제, 수정 기능 구현
- 직원 정보는 employee 테이블에 저장된다.
- 지역 정보는 region 테이블에 저장된다.
- 부서 정보는 department 테이블에 저장된다.
- 직위 정보는 position 테이블에 저장된다.
- 직원 정보 입력 항목은 직원 번호, 이름, 주민번호(암호화 기능), 생년월일(jQuery 달력 기능), 양음력, 전화번호, 부서아이디, 직위아이디, 지역아이디, 기본급, 수당으로 구성
- 직원 정보 입력시 기본급은 직위별 최소 기본급 이상 입력되도록 한다(Ajax 기능 이용).
- 직원 정보 출력 항목은 직원 번호, 이름, 생년월일, 양음력, 전화번호, 부서명, 직위명, 지역명, 기본급, 수당, 급여로 구성
- 직원 정보 출력시 항목별 정렬 기능 구현
- 직원 정보 검색은 사번, 주민번호, 이름, 부서, 지역, 직위 등의 항목을 기준으로 검색 결과를 출력하도록 구현
- 직원 삭제는 사번(PK)을 기준으로 삭제할 수 있도록 구현
- 직원 수정은 사번(PK)을 기준으로 수정할 수 있도록 구현


2. 직원 정보
- 직원 번호, 이름, 주민번호, 생년월일, 양음력, 전화번호, 부서, 직위, 지역, 기본급, 수당, 급여(기본급+수당)
- 부서 : 개발부, 마케팅부, 영업부
- 직위 : 사원, 대리, 과장, 부장
- 지역 : 서울, 경기, 인천, ...
- 기본급 : 직위별 최소 기본급 이상

3. 부서 정보 출력, 입력, 삭제, 수정 기능 구현
- 부서번호, 부서이름, 삭제가능여부, 수정 기능 추가

4. 직위 정보 출력, 입력, 삭제, 수정 기능 구현
- 직위번호, 직위이름, 최소기본급, 삭제가능여부, 수정 기능 추가

5. 지역 정보 출력, 입력, 삭제, 수정 기능 구현
- 지역번호, 지역이름, 삭제가능여부, 수정 기능 추가

6. 관리자, 일반 직원 로그인 과정 추가
- 관리자 로그인한 경우는 모든 기능 사용 가능.
- 일반 직원 로그인한 경우는 일부 기능 사용 가능. 직원 정보 일부 출력 기능으로 한정. 직원 정보 일부 출력 항목은 직원 번호, 이름, 생년월일, 양음력, 전화번호, 부서명, 직위명, 지역명로 구성. 검색 기능 추가. 사번, 이름, 부서, 지역, 직위 등의 항목을 기준으로 검색 결과를 출력하도록 구현

7. 데이터베이스 구성 (employee, region, position, department)

--지역 정보 테이블
CREATE TABLE region (
 regionId NUMBER --PK
 , regionName NVARCHAR2(30)
);

ALTER TABLE region
 ADD CONSTRAINT region_id_pk
  PRIMARY KEY(regionId);

CREATE SEQUENCE regionSeq;

INSERT INTO region (regionId, regionName)
 VALUES (regionSeq.nextval, '서울');
INSERT INTO region (regionId, regionName)
 VALUES (regionSeq.nextval, '경기');
INSERT INTO region (regionId, regionName)
 VALUES (regionSeq.nextval, '인천');
COMMIT;


--직위 정보 테이블
CREATE TABLE position (
 positionId NUMBER --PK
 , positionName NVARCHAR2(30)
 , minBasicPay NUMBER
);

ALTER TABLE position
 ADD CONSTRAINT position_id_pk
  PRIMARY KEY(positionId);

CREATE SEQUENCE positionSeq;

INSERT INTO position (positionId, positionName, minBasicPay)
 VALUES (positionSeq.nextval, '사원', 1000000);
INSERT INTO position (positionId, positionName, minBasicPay)
 VALUES (positionSeq.nextval, '대리', 2000000);
INSERT INTO position (positionId, positionName, minBasicPay)
 VALUES (positionSeq.nextval, '부장', 3000000);
COMMIT;


--부서 정보 테이블
CREATE TABLE department (
 departmentId NUMBER --PK
 , departmentName NVARCHAR2(30)
);

ALTER TABLE department
 ADD CONSTRAINT department_id_pk
  PRIMARY KEY(departmentId);

CREATE SEQUENCE departmentSeq;

INSERT INTO department (departmentId, departmentName)
 VALUES (departmentSeq.nextval, '개발부');
INSERT INTO department (departmentId, departmentName)
 VALUES (departmentSeq.nextval, '마케팅부');
INSERT INTO department (departmentId, departmentName)
 VALUES (departmentSeq.nextval, '영업부');
COMMIT;


--직원 정보 테이블
--직원 번호, 이름, 주민번호, 생년월일, 양음력, 전화번호, 부서, 직위, 지역, 기본급, 수당
CREATE TABLE employee (
 employeeId NUMBER --PK
 ,name NVARCHAR2(10)
 ,ssn VARCHAR2(30) --오라클 암호화 기능 추가
 ,birthday DATE
 ,lunar NUMBER(1)  --양력 0, 음력 1
 ,telephone VARCHAR2(30)
 ,departmentId NUMBER --FK
 ,positionId NUMBER --FK
 ,regionId NUMBER --FK
 ,basicPay NUMBER
 ,extraPay NUMBER
);

ALTER TABLE employee
 ADD CONSTRAINT EMPLOYEE_ID_PK
  PRIMARY KEY(employeeId);
ALTER TABLE employee
 ADD CONSTRAINT employee_departmentId_fk
  FOREIGN KEY (departmentId)
  REFERENCES department(departmentId);
ALTER TABLE employee
 ADD CONSTRAINT employee_positionId_fk
  FOREIGN KEY (positionId)
  REFERENCES position(positionId);
ALTER TABLE employee
 ADD CONSTRAINT employee_regionId_fk
  FOREIGN KEY (regionId)
  REFERENCES region(regionId);
ALTER TABLE employee
 ADD CONSTRAINT employee_lunar_ck
  CHECK (lunar=0 OR lunar=1);


CREATE SEQUENCE employeeSeq;

INSERT INTO employee (employeeId
  ,name
  ,ssn
  ,birthday
  ,lunar
  ,telephone
  ,departmentId
  ,positionId
  ,regionId
  ,basicPay
  ,extraPay)
 VALUES (employeeSeq.nextval
  , '홍길동'
  , encrypt('8012121122345', '홍길동')
  , '1980-12-12'
  , 0   --양력 0, 음력 1
  , '010-123-1234'
  , 1  --departmentId FK
  , 1  --positionId FK
  , 1  --regionId FK
  , 1500000
  , 1000000);
INSERT INTO employee (employeeId
  ,name
  ,ssn
  ,birthday
  ,lunar
  ,telephone
  ,departmentId
  ,positionId
  ,regionId
  ,basicPay
  ,extraPay)
 VALUES (employeeSeq.nextval
  , '박길동'
  , encrypt('8201101234567', '박길동')
  , '1982-01-10'
  , 1   --양력 0, 음력 1
  , '010-456-4567'
  , 2  --departmentId FK
  , 1  --positionId FK
  , 2  --regionId FK
  , 1800000
  , 1000000);
COMMIT;


--직원 정보 출력 쿼리 (JOIN, SubQuery)
직원 번호, 이름, 생년월일, 양음력, 전화번호, 부서명, 직위명, 지역명, 기본급, 수당, 급여(기본급+수당)

SELECT employeeId
 , name
 , ssn
 , TO_CHAR(birthday, 'yyyy-mm-dd') AS birthday
 , lunar
 , DECODE(lunar, 0, '양력', '음력') AS lunarName
 , telephone
 , departmentId
 , (SELECT departmentName FROM department
  WHERE departmentId=e.departmentId )
  AS departmentName
 , positionId
 , (SELECT positionName FROM position
  WHERE positionId=e.positionId )
  AS positionName
 , regionId
 , (SELECT regionName FROM region
  WHERE regionId=e.regionId )
  AS regionName
 , basicPay
 , extraPay
 , (basicPay + extraPay) AS pay
 FROM employee e
 ORDER BY employeeId;
--> 뷰 생성
CREATE OR REPLACE VIEW employeeView
AS
SELECT employeeId
 , name
 , ssn
 , TO_CHAR(birthday, 'yyyy-mm-dd') AS birthday
 , lunar
 , DECODE(lunar, 0, '양력', '음력') AS lunarName
 , telephone
 , departmentId
 , (SELECT departmentName FROM department
  WHERE departmentId=e.departmentId )
  AS departmentName
 , positionId
 , (SELECT positionName FROM position
  WHERE positionId=e.positionId )
  AS positionName
 , regionId
 , (SELECT regionName FROM region
  WHERE regionId=e.regionId )
  AS regionName
 , basicPay
 , extraPay
 , (basicPay + extraPay) AS pay
 FROM employee e;
-->뷰를 이용해서 SELECT 쿼리 실행
SELECT employeeId
 , name
 , birthday
 , lunar
 , lunarName
 , telephone
 , departmentId
 , departmentName
 , positionId
 , positionName
 , regionId
 , regionName
 , basicPay
 , extraPay
 , pay
 FROM employeeView
 ORDER BY employeeId;


--직원 정보 검색 쿼리
SELECT employeeId
 , name
 , birthday
 , lunar
 , lunarName
 , telephone
 , departmentId
 , departmentName
 , positionId
 , positionName
 , regionId
 , regionName
 , basicPay
 , extraPay
 , pay
 FROM employeeView e
   --WHERE ssn=encrypt('8012121122345',e.name)
 --WHERE employeeId=1
 --WHERE name='홍길동'
 --WHERE regionName='서울'
 --WHERE departmentName='개발부'
 WHERE positionName='사원'
 ORDER BY employeeId;

 


--지역 정보 출력
SELECT regionId, regionName
  , (SELECT COUNT(*) FROM employee
      WHERE regionId=r.regionId) AS delCheck
FROM region r
ORDER BY regionId;
-->뷰 생성
CREATE OR REPLACE VIEW regionView
AS
SELECT regionId, regionName
  , (SELECT COUNT(*) FROM employee
      WHERE regionId=r.regionId) AS delCheck
FROM region r;
-->뷰를 이용한 SELECT 쿼리
SELECT regionId, regionName, delCheck
 FROM regionView
 ORDER BY regionId;

 

 

--부서 정보 출력
SELECT departmentId, departmentName
  , (SELECT COUNT(*) FROM employee
      WHERE departmentId=r.departmentId) AS delCheck
FROM department r
ORDER BY departmentId;
-->뷰 생성
CREATE OR REPLACE VIEW departmentView
AS
SELECT departmentId, departmentName
  , (SELECT COUNT(*) FROM employee
      WHERE departmentId=r.departmentId) AS delCheck
FROM department r;
-->뷰를 이용한 SELECT 쿼리
SELECT departmentId, departmentName, delCheck
 FROM departmentView
 ORDER BY departmentId;

 


--직위 정보 출력
SELECT positionId, positionName, minBasicPay
  , (SELECT COUNT(*) FROM employee
      WHERE positionId=r.positionId) AS delCheck
FROM position r
ORDER BY positionId;
-->뷰 생성
CREATE OR REPLACE VIEW positionView
AS
SELECT positionId, positionName, minBasicPay
  , (SELECT COUNT(*) FROM employee
      WHERE positionId=r.positionId) AS delCheck
FROM position r;
-->뷰를 이용한 SELECT 쿼리
SELECT positionId, positionName, minBasicPay, delCheck
 FROM positionView
 ORDER BY positionId;


--최소기본급 검색 쿼리
SELECT minBasicPay
 FROM positionView
 WHERE positionId=1;

 

--------------------------------------
--관리자 기능 부여를 위해서 grade 컬럼 추가
--관리자 0, 일반 1
ALTER TABLE employee
 ADD (grade NUMBER(1) DEFAULT 1);

UPDATE employee SET grade=0
 WHERE employeeId=1;
COMMIT;


CREATE OR REPLACE VIEW employeeView
AS
SELECT employeeId
 , name
 , ssn
 , TO_CHAR(birthday, 'yyyy-mm-dd') AS birthday
 , lunar
 , DECODE(lunar, 0, '양력', '음력') AS lunarName
 , telephone
 , departmentId
 , (SELECT departmentName FROM department
  WHERE departmentId=e.departmentId )
  AS departmentName
 , positionId
 , (SELECT positionName FROM position
  WHERE positionId=e.positionId )
  AS positionName
 , regionId
 , (SELECT regionName FROM region
  WHERE regionId=e.regionId )
  AS regionName
 , basicPay
 , extraPay
 , (basicPay + extraPay) AS pay
 , grade
 FROM employee e;
-->뷰를 이용해서 SELECT 쿼리 실행
SELECT employeeId
 , name
 , birthday
 , lunar
 , lunarName
 , telephone
 , departmentId
 , departmentName
 , positionId
 , positionName
 , regionId
 , regionName
 , basicPay
 , extraPay
 , pay
 , grade
 FROM employeeView
 ORDER BY employeeId;


--관리자 아이디(이름), 패스워드(주민번호) 검사 쿼리
SELECT COUNT(*) AS count
 FROM employeeView
 WHERE name='아이디'
  AND ssn=encrypt('패스워드', '아이디')
  AND grade=0;


--일반직원 아이디(이름), 패스워드(주민번호) 검사 쿼리
SELECT COUNT(*) AS count
 FROM employeeView
 WHERE name='아이디'
  AND ssn=encrypt('패스워드', '아이디');


-----------------------------------------
수정 기능 추가

--직원 정보 수정 쿼리
UPDATE employee SET birthday='1980-12-12'
  ,lunar=0
  ,telephone='010-456-4567'
  ,departmentId=1
  ,positionId=1
  ,regionId=1
  ,basicPay=1500000
  ,extraPay=1000000
  ,grade=0
 WHERE employeeId=1 and ssn=encrypt('8012121122345', '홍길동');


--지역 정보 수정 쿼리
UPDATE region SET regionName='지역이름'
 WHERE regionId=번호;

--부서 정보 수정 쿼리
UPDATE department SET departmentName='부서이름'
 WHERE departmentId=번호;

--직위 정보 수정 쿼리
UPDATE position SET positionName='직위이름'
  , minBasicPay=최소기본급
 WHERE positionId=번호;
COMMIT;


8. 화면 구성
----------------------------------------------------
[직원관리] [지역관리] [부서관리] [직위관리]
---------------------------------------------------
-직원관리-

[직원추가] [직원검색]

직원수 : 1 명

직원 번호, 이름, 생년월일, 양음력, 전화번호, 부서명, 직위명, 지역명, 기본급, 수당, 급여, 삭제 수정
--------------------------------------------------------------------------------------------------------
1, 홍길동, 1980-12-12, 양력, 010-123-1234, 개발부, 사원, 서울, 1,500,000, 1,000,000, 2,500,000, [삭제], [수정]

 

 

---------------------------------------------------
[직원관리] [지역관리] [부서관리] [직위관리]
---------------------------------------------------
-직원관리-

[직원명단][직원검색]

이름* [박길동]
주민등록번호(YYMMDD-NNNNNNN)* [800110-1234567]
생년월일* [2010-10-10] <-달력 호출
양음력* o 양력 o 음력
전화번호(010-XXXX-XXXX)* [010-345-6789]
지역* [서울] <-선택 목록
부서* [개발부] <-선택 목록
직위* [사원] <- 선택 목록
기본급(최소 2000000원 이상)* [2000000] <-Ajax
수당* [100000]

[직원추가]

 


---------------------------------------------------
[직원관리] [지역관리] [부서관리] [직위관리]
---------------------------------------------------
-직원관리-

[직원명단][직원추가]

검색기준  o사번 o주민번호 o이름 o지역 o부서 o직위
검색단어 [       ] [직원검색]

검색 직원수 : 1 명

직원 번호, 이름, 생년월일, 양음력, 전화번호, 부서명, 직위명, 지역명, 기본급, 수당, 급여, 삭제, 수정
------------------------------------------------------------------------------------------------
1, 홍길동, 1980-12-12, 양력, 010-123-1234, 개발부, 사원, 서울, 1,500,000, 1,000,000, 2,500,000, [삭제], [수정]

 

 


---------------------------------------------------
[직원관리] [지역관리] [부서관리] [직위관리]
---------------------------------------------------
-지역관리-

지역번호 [    ]  지역명 [       ] [지역추가] [지역수정]

지역번호, 지역명, 삭제
-----------------
1, 서울, [삭제] <-비활성
2, 경기, [삭제]
3, 인천, [삭제]

 


---------------------------------------------------
[직원관리] [지역관리] [부서관리] [직위관리]
---------------------------------------------------
-부서관리-

부서번호 [    ]  부서명 [       ] [부서추가] [부서수정]

부서번호, 부서명, 삭제
-----------------
1, 개발부, [삭제] <-비활성
2, 마케팅부, [삭제]
3, 영업부, [삭제]

 

 

---------------------------------------------------
[직원관리] [지역관리] [부서관리] [직위관리]
---------------------------------------------------
-직위관리-

직위번호 [    1]  직위명 [    사원   ] 최소기본급 [ 1500000   ] [직위추가] [직위수정]

직위번호, 직위명, 최소기본급, 삭제
-------------------------
1, 사원, 1000000, [삭제] <-비활성
2, 대리, 2000000, [삭제]
3, 부장, 3000000, [삭제]

 

---------------------------------------------------
[직원관리] [지역관리] [부서관리] [직위관리]
---------------------------------------------------
-직원관리-

[직원명단][직원검색]

직원번호 [1001] <-readonly
이름* [박길동] <-readonly
주민등록번호(YYMMDD-NNNNNNN)* [8001101234567] <-재입력
생년월일* [2010-10-10] <-달력 호출
양음력* o 양력 o 음력
전화번호(010-XXXX-XXXX)* [새로운 전화번호]
지역* [서울] <-선택 목록
부서* [개발부] <-선택 목록
직위* [사원] <- 선택 목록
기본급(최소 2000000원 이상)* [2000000] <-Ajax
수당* [100000]
등급*  o일반직원 o관리자

[직원수정]

 


로그인 화면 추가
아이디 [     ]
패스워드 [      ]
[로그인]


9. 프로그램 구성

//DBConn.java

//Employee.java -> 직원 정보 자료형 클래스
//Region.java -> 지역 정보 자료형 클래스
//Position.java -> 직위 정보 자료형 클래스
//Department.java -> 부서 정보 자료형 클래스

//EmployeeDAO.java -> JDBC 액션 클래스. 직원 정보 입출력 액션. 수정 메소드 추가
//RegionDAO.java -> JDBC 액션 클래스. 지역 정보 입출력 액션. 수정 메소드 추가
//PositionDAO.java -> JDBC 액션 클래스. 직위 정보 입출력 액션. 수정 메소드 추가
//DepartmentDAO.java -> JDBC 액션 클래스. 부서 정보 입출력 액션. 수정 메소드 추가

//Controller.java -> 서블릿 클래스. 요청 주소 분석 및 처리.
//Action.java -> 액션 처리. 액션 메소드 추가
//web.xml -> 서블릿 주소 등록. 확장자 .it 주소 등록.

//EmployeeMenu.jsp -> 메인 메뉴 페이지. 로그아웃 버튼.

//EmployeeList.jsp -> 직원 정보 출력 페이지. 삭제 버튼. 수정 버튼.
//EmployeeSearch.jsp -> 직원 정보 검색 페이지
//EmployeeInsertForm.jsp -> 직원 정보 입력 폼
//EmployeeUpdateForm.jsp -> 직원 정보 수정 폼

//RegionList.jsp -> 지역 정보 출력 페이지. 입력 폼 페이지. 삭제 버튼. 수정 버튼.

//PositionList.jsp -> 직위 정보 출력 페이지. 입력 폼 페이지. 삭제 버튼. 수정 버튼.

//DepartmentList.jsp -> 부서 정보 출력 페이지. 입력 폼 페이지. 삭제 버튼. 수정 버튼.

//PositionReceive.jsp -> Ajax 응답 페이지.

//LoginForm.jsp -> 관리자, 일반 직원 로그인 폼 페이지. 아이디(name), 패스워드(ssn) 입력.
//LogoutForm.jsp -> 로그아웃 메시지 출력 페이지.
//LoginFail.jsp -> 로그인 실패 메시지 출력 페이지.

//EmpList.jsp -> 일반 직원 전용 출력 페이지. 로그아웃 버튼. 입력, 삭제, 수정 기능 없음.

//Error.jsp -> 잘못된 요청 주소 메시지 출력 페이지.


10. 소스코드


//RegionDAO.java -> modify() 메소드 추가
package com.test;

import java.sql.*;
import java.util.*;

//데이터베이스 액션 클래스
public class RegionDAO {

 //지역 명단 출력 메소드
 public ArrayList<Region> regionList() {
  
  ArrayList<Region> result = new ArrayList<Region>();

  Connection conn = null;
  PreparedStatement pstmt = null;
  try {
   conn = DBConn.getConnection(); 
   
   //SELECT regionId, regionName, delCheck
   // FROM regionView
   // ORDER BY regionId;
   String sql = "SELECT regionId, regionName, delCheck FROM regionView ORDER BY regionId";
   pstmt = conn.prepareStatement(sql);
   ResultSet rs = pstmt.executeQuery();
   while(rs.next()) {
    Region r = new Region();
    r.setRegionId(rs.getString("regionId"));
    r.setRegionName(rs.getString("regionName"));
    r.setDelCheck(rs.getInt("delCheck"));
    result.add(r);
   }
   rs.close();
  
  }catch(Exception e){
   e.printStackTrace();
  }finally{
   try {
    if (pstmt != null) {
     pstmt.close();
    }
   }catch(Exception e){
   }
   
   DBConn.close();   
  }   
  
  return result;
 }
 
 //지역 명단 입력 메소드
 public int add(Region region) {
  int result = 0;
  
  Connection conn = null;
  PreparedStatement pstmt = null;
  try {
   conn = DBConn.getConnection(); 
   
   //INSERT INTO region (regionId, regionName)
   // VALUES (regionSeq.nextval, ?)
   String sql = "INSERT INTO region (regionId, regionName) VALUES (regionSeq.nextval, ?)";
   pstmt = conn.prepareStatement(sql);
   pstmt.setString(1, region.getRegionName());
   result = pstmt.executeUpdate();
   
  }catch(Exception e){
   e.printStackTrace();
  }finally{
   try {
    if (pstmt != null) {
     pstmt.close();
    }
   }catch(Exception e){
   }
   
   DBConn.close();   
  }   
  
  return result;
 }
 
 //지역 명단 삭제 메소드 -> 외부에서 지역번호를 전달 받아야 한다.
 public int remove(String regionId) {
  int result = 0;
  
  Connection conn = null;
  PreparedStatement pstat = null;
  
  try {
   conn = DBConn.getConnection();
   String sql = "DELETE FROM region WHERE regionId = ?";
   pstat = conn.prepareStatement(sql);
   pstat.setString(1, regionId);
   result = pstat.executeUpdate();
  }catch(Exception e){
   e.printStackTrace();
  }finally{
   try{
    if(pstat!=null){
     pstat.close();
    }
   }catch(Exception e){
   }
   DBConn.close();
  }  
  return result;
 }
  
 
 
 //지역 명단 수정 메소드
 public int modify(Region region) {
  int result = 0;
  
  Connection conn = null;
  PreparedStatement pstmt = null;
  try {
   conn = DBConn.getConnection(); 
   
   //UPDATE region SET regionName=? WHERE regionId=?
   String sql = "UPDATE region SET regionName=? WHERE regionId=?";
   pstmt = conn.prepareStatement(sql);
   pstmt.setString(1, region.getRegionName());
   pstmt.setString(2, region.getRegionId());
   result = pstmt.executeUpdate();
   
  }catch(Exception e){
   e.printStackTrace();
  }finally{
   try {
    if (pstmt != null) {
     pstmt.close();
    }
   }catch(Exception e){
   }
   
   DBConn.close();   
  }   
  
  return result;
 }
 
}

 

 

 


//Action.java
package com.test;

import java.io.*;
import java.util.ArrayList;

import javax.servlet.*;
import javax.servlet.http.*;

//액션 전용 클래스 -> 메소드 단위로 액션 처리
public class Action {
 
 /*
 public String 메소드이름(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  return "요청주소.jsp";
  //return "redirect:요청주소";
 }
 */

 public String regionList(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //액션 및 결과 출력
  RegionDAO dao = new RegionDAO();
  request.setAttribute("regionList",  dao.regionList());
  return "WEB-INF/source/RegionList.jsp";
 }

 
 public String regionInsert(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //액션 전용
  
  //데이터 수신(한글 인코딩 추가)
  request.setCharacterEncoding("UTF-8");
  String regionName = request.getParameter("regionName");

  //데이터베이스 액션 -> add() 메소드 호출로 대체
  RegionDAO dao = new RegionDAO();
  Region r = new Region();
  r.setRegionName(regionName);
  dao.add(r);
  
  return "redirect:RegionList.it";
 }
 
 public String regionDelete(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //액션 전용

  //데이터 수신(한글 인코딩 추가)
  request.setCharacterEncoding("UTF-8");
  String regionId = request.getParameter("regionId");

  //데이터베이스 액션 -> add() 메소드 호출로 대체
  RegionDAO dao = new RegionDAO();
  dao.remove(regionId);
  
  return "redirect:RegionList.it";
 }
 
 public String regionUpdate(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //액션 전용
  
  //데이터 수신(한글 인코딩 추가)
  request.setCharacterEncoding("UTF-8");
  String regionId = request.getParameter("regionId");
  String regionName = request.getParameter("regionName");

  //데이터베이스 액션 -> modify() 메소드 호출로 대체
  RegionDAO dao = new RegionDAO();
  Region r = new Region();
  r.setRegionId(regionId);
  r.setRegionName(regionName);
  dao.modify(r);
  
  return "redirect:RegionList.it";
 }
 
 

}

 

 

//Controller.java
package com.test;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.*;

public class Controller extends HttpServlet {

 private static final long serialVersionUID = 1L;

 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  doGetPost(req, resp);
 }

 @Override
 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  doGetPost(req, resp);
 }
 
 private void doGetPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  //요청 주소 분석 및 액션 메소드 호출
  String uri = request.getRequestURI();
  //->"http://localhost:8090/프로젝트이름/Sample.it"
  
  Action action = new Action();
  String result = "Error.jsp";

  //요청주소별로 작성할 것.
  if (uri.indexOf("RegionList.it") != -1) {
   //액션 메소드 호출
   //메소드 결과는 URI 주소 형태를 가지고 있다.
   result = action.regionList(request, response);
  }
  if (uri.indexOf("RegionInsert.it") != -1) {
   result = action.regionInsert(request, response);
  }
  if (uri.indexOf("RegionDelete.it") != -1) {
   result = action.regionDelete(request, response);
  }
  if (uri.indexOf("RegionUpdate.it") != -1) {
   result = action.regionUpdate(request, response);
  }
  
  //페이지 전환 -> forward(), sendRedirect() 메소드
  if (result.indexOf("redirect:") != -1) {
   //sendRedirect 요청
   //->또 다른 서블릿 주소 요청
   response.sendRedirect(result.substring(9));
  } else {
   //forward 요청
   //->연관된 JSP 페이지 요청
   RequestDispatcher dispatcher = request.getRequestDispatcher(result);
   dispatcher.forward(request, response);
  }
  
 }

}

 

 

 

//RegionList.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>직원 관리(Servlet MVC 버전)</title>

<link rel="stylesheet" type="text/css" href="TableStyle.css">
<link rel="stylesheet" type="text/css" href="DivStyle.css">

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script type="text/javascript">
//jQuery 버전
$(document).ready(function(){
 //지역 추가 액션->지역명 빈 항목 검사
 $("#btnAdd").click(function(){
  if($("#regionName").val()==""){
   alert("지역명을 입력하시오!");
  } else {
   //서브밋 액션 진행
   $("#myForm").attr("action", "RegionInsert.it");
   $("#myForm").submit();
  }
 }); 
 //지역 수정 액션->지역번호(기존), 지역명(신규) 빈 항목 검사
 $("#btnModify").click(function(){
  if($("#regionId").val()==""
    || $("#regionName").val()==""){
   alert("지역번호, 지역명을 입력하시오!");
  } else {
   var num = $("#regionId").val();
   if(confirm(num+"번 지역을 수정할까요?")){
    //서브밋 액션 진행
    $("#myForm").attr("action", "RegionUpdate.it");
    $("#myForm").submit();
   }
  }
 }); 
 //삭제 버튼 액션 추가
 $(".btnDelete").click(function(){
  var num = $(this).parent().parent().find("td:first").text();
  if(confirm(num+"번 지역을 삭제할까요?")){
   $(location).attr("href", "RegionDelete.it?regionId="+num);
  }
 });
 
});
 
</script>

</head>
<body>
 <div>
  <!-- 메뉴 영역 -->
  <div class="title">
   <h1>직원관리 (Servlet MVC 버전)</h1>
   <!-- import 구문에서만 확장자 .jsp 유지한다. -->
   <c:import url="EmployeeMenu.jsp"></c:import>
  </div>

  <!-- 콘텐츠 영역 -->
  <div class="main">
   <h2>지역 관리</h2>
   
   <!-- action="" 속성의 요청 주소를 jQuery에서 결정 -->
   <form method="post" id="myForm">
    <!-- name="", id="" 식별자는 테이블 컬럼명 사용 -->
    지역번호* <input type="text" name="regionId" id="regionId">
    지역명* <input type="text" name="regionName" id="regionName">
    
    <!-- submit 액션을 jQuery에서 결정 -->
    <input type="button" id="btnAdd" value="지역추가">
    <input type="button" id="btnModify" value="지역수정">
    
    <span id="errorMsg" style="color:red;"></span>
   </form>
   <table id="t01" style="font-size:10pt;">
    <!-- <tr>은 제목 -->
    <tr>
     <th>지역 번호</th>
     <th>지역명</th>
     <th>삭제</th>
    </tr>
    <c:forEach var="r" items="${regionList}">
    <tr>
     <td>${r.regionId}</td>
     <td>${r.regionName}</td>
     <td><input type="button" value="삭제"
       class="btnDelete"
       ${r.delCheck==0?"":"disabled=\"disabled\""} ></td>
    </tr>
    </c:forEach>
    
   </table>
  </div>
 </div>
 

 
</body>
</html>

 


----------------------------------------
문제) 부서관리, 직위관리 Servlet MVC 버전 작성. 출력, 입력, 삭제, 수정 기능.

//PositionDAO.java -> modify() 메소드 추가
//DepartmentDAO.java -> modify() 메소드 추가

//Controller.java -> 액션 주소 추가
//Action.java -> 액션 메소드 추가

//DepartmentList.jsp -> 기존 JSP 코드 삭제, JSTL, EL 표현 추가
//PositionList.jsp -> 기존 JSP 코드 삭제, JSTL, EL 표현 추가


---------------------------------------
//PositionDAO.java -> modify() 메소드 추가
package com.test;

import java.util.*;
import java.sql.*;

public class PositionDAO {

 public ArrayList<Position> positionList() {

  ArrayList<Position> result = new ArrayList<Position>();

  Connection conn = null;
  PreparedStatement pstat = null;

  try {
   conn = DBConn.getConnection();
   String sql = "SELECT positionId, positionName, minBasicPay, delCheck FROM positionView ORDER BY positionId";
   pstat = conn.prepareStatement(sql);
   ResultSet rs = pstat.executeQuery();
   while (rs.next()) {
    Position p = new Position();
    p.setPositionId(rs.getString("positionId"));
    p.setPositionName(rs.getString("positionName"));
    p.setMinBasicPay(rs.getInt("minBasicPay"));
    p.setDelCheck(rs.getInt("delCheck"));
    result.add(p);
   }
   rs.close();
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   try {
    if (pstat != null) {
     pstat.close();
    }
   } catch (Exception e) {
   }
   DBConn.close();
  }
  return result;
 }

 // 직위 명단 입력 메소드
 public int add(Position p) {
  int result = 0;

  Connection conn = null;
  PreparedStatement pstat = null;

  try {
   conn = DBConn.getConnection();
   String sql = "INSERT INTO position (positionId, positionName, minBasicPay) "
     + "VALUES ((SELECT NVL(MAX(positionId), 0)+1 FROM position), ?, ?)";
   pstat = conn.prepareStatement(sql);
   pstat.setString(1, p.getPositionName());
   pstat.setInt(2, p.getMinBasicPay());
   result = pstat.executeUpdate();
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   try {
    if (pstat != null) {
     pstat.close();
    }
   } catch (Exception e) {
   }
   DBConn.close();
  }
  return result;
 }

 // 직위 명단 삭제 메소드 -> 외부에서 직위번호를 전달 받아야 한다.
 public int remove(String positionId) {
  int result = 0;

  Connection conn = null;
  PreparedStatement pstat = null;

  try {
   conn = DBConn.getConnection();
   String sql = "DELETE FROM position WHERE positionId = ?";

   pstat = conn.prepareStatement(sql);
   pstat.setString(1, positionId);
   result = pstat.executeUpdate();
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   try {
    if (pstat != null) {
     pstat.close();
    }
   } catch (Exception e) {
   }
   DBConn.close();
  }
  return result;
 }

 // 직위 명단 수정 메소드
 public int modify(Position p) {
  int result = 0;

  Connection conn = null;
  PreparedStatement pstat = null;

  try {
   conn = DBConn.getConnection();
   String sql = "UPDATE position SET positionName=?, minBasicPay=? WHERE positionId=?";
   pstat = conn.prepareStatement(sql);
   pstat.setString(1, p.getPositionName());
   pstat.setInt(2, p.getMinBasicPay());
   pstat.setString(3, p.getPositionId());
   result = pstat.executeUpdate();
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   try {
    if (pstat != null) {
     pstat.close();
    }
   } catch (Exception e) {
   }
   DBConn.close();
  }
  return result;
 }
}

 

 

 

//DepartmentDAO.java -> modify() 메소드 추가
package com.test;

import java.util.*;
import java.sql.*;

//데이터베이스 액션 클래스
public class DepartmentDAO {

 public ArrayList<Department> departmentList() {

  ArrayList<Department> result = new ArrayList<Department>();

  Connection conn = null;
  PreparedStatement pstat = null;

  try {
   conn = DBConn.getConnection();
   String sql = "SELECT departmentId, departmentName, delCheck FROM departmentView ORDER BY departmentId";
   pstat = conn.prepareStatement(sql);
   ResultSet rs = pstat.executeQuery();
   while (rs.next()) {
    Department d = new Department();
    d.setDepartmentId(rs.getString("departmentId"));
    d.setDepartmentName(rs.getString("departmentName"));
    d.setDelCheck(rs.getInt("delCheck"));
    result.add(d);
   }
   rs.close();
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   try {
    if (pstat != null) {
     pstat.close();
    }
   } catch (Exception e) {
   }
   DBConn.close();
  }
  return result;
 }

 // 부서 명단 입력 메소드
 public int add(Department d) {
  int result = 0;

  Connection conn = null;
  PreparedStatement pstat = null;

  try {
   conn = DBConn.getConnection();
   String sql = "INSERT INTO department (departmentId, departmentName) VALUES ((SELECT NVL(MAX(departmentId),0)+1 FROM department), ?)";
   pstat = conn.prepareStatement(sql);
   pstat.setString(1, d.getDepartmentName());
   result = pstat.executeUpdate();
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   try {
    if (pstat != null) {
     pstat.close();
    }
   } catch (Exception e) {
   }
   DBConn.close();
  }
  return result;
 }

 // 부서 명단 삭제 메소드 -> 외부에서 부서번호를 전달 받아야 한다.
 public int remove(String departmentId) {
  int result = 0;

  Connection conn = null;
  PreparedStatement pstat = null;

  try {
   conn = DBConn.getConnection();
   String sql = "DELETE FROM department WHERE departmentId = ?";
   pstat = conn.prepareStatement(sql);
   pstat.setString(1, departmentId);
   result = pstat.executeUpdate();
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   try {
    if (pstat != null) {
     pstat.close();
    }
   } catch (Exception e) {
   }
   DBConn.close();
  }
  return result;
 }

 // 부서 명단 수정 메소드
 public int modify(Department d) {
  int result = 0;

  Connection conn = null;
  PreparedStatement pstat = null;

  try {
   conn = DBConn.getConnection();
   String sql = "UPDATE department SET departmentName=? WHERE departmentId=?";
   pstat = conn.prepareStatement(sql);
   pstat.setString(1, d.getDepartmentName());
   pstat.setString(2, d.getDepartmentId());
   result = pstat.executeUpdate();
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   try {
    if (pstat != null) {
     pstat.close();
    }
   } catch (Exception e) {
   }
   DBConn.close();
  }
  return result;
 }
}

 

 

 


//Controller.java -> 액션 주소 추가
package com.test;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.*;
import com.sun.corba.se.spi.orbutil.fsm.*;

public class Controller extends HttpServlet {

 private static final long serialVersionUID = 1L;

 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  doGetPost(req, resp);
 }

 @Override
 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  doGetPost(req, resp);
 }

 private void doGetPost(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {

  // 요청 주소 분석 및 액션 메소드 호출
  String uri = request.getRequestURI();
  // -> "http://localhost:8090/프로젝트이름/Sample.it"

  Action action = new Action();
  String result = "Error.jsp";

  //요청 주소별로 작성할 것.
  if (uri.indexOf("RegionList.it") != -1) {
   // 액션 메소드 호출
   // 메소드 결과는 URI 주소 형태를 가지고 있다.
   result = action.regionList(request, response);
  }
  
  if (uri.indexOf("RegionInsert.it") != -1) {
   result = action.regionInsert(request, response);
  }
  
  if (uri.indexOf("RegionDelete.it") != -1) {
   result = action.regionDelete(request, response);
  }
  
  if (uri.indexOf("RegionUpdate.it") != -1) {
   result = action.regionUpdate(request, response);
  }
  
  if (uri.indexOf("PositionList.it") != -1) {
   // 액션 메소드 호출
   // 메소드 결과는 URI 주소 형태를 가지고 있다.
   result = action.positionList(request, response);
  }
  
  if (uri.indexOf("PositionInsert.it") != -1) {
   result = action.positionInsert(request, response);
  }
  
  if (uri.indexOf("PositionDelete.it") != -1) {
   result = action.positionDelete(request, response);
  }
  
  if (uri.indexOf("PositionUpdate.it") != -1) {
   result = action.positionUpdate(request, response);
  }
  
  if (uri.indexOf("DepartmentList.it") != -1) {
   // 액션 메소드 호출
   // 메소드 결과는 URI 주소 형태를 가지고 있다.
   result = action.departmentList(request, response);
  }
  
  if (uri.indexOf("DepartmentInsert.it") != -1) {
   result = action.departmentInsert(request, response);
  }
  
  if (uri.indexOf("DepartmentDelete.it") != -1) {
   result = action.departmentDelete(request, response);
  }
  
  if (uri.indexOf("DepartmentUpdate.it") != -1) {
   result = action.departmentUpdate(request, response);
  }

  // 페이지 전환 -> forward(), sendRedirect() 메소드
  if (result.indexOf("redirect:") != -1) {
   // sendRedirect 요청
   // -> 또 다른 서블릿 주소 요청
   response.sendRedirect(result.substring(9));
  } else {
   // forward 요청
   // -> 연관된 JSP 페이지 요청
   RequestDispatcher dispatcher = request.getRequestDispatcher(result);
   dispatcher.forward(request, response);
  }
 }

}

 

 

//Action.java -> 액션 메소드 추가
package com.test;

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

//액션 전용 클래스 -> 메소드 단위로 액션 처리
public class Action {

 /*
 public String 메소드이름(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
  
  return "요청주소";
  //return "redirect:요청주소";
  //->액션 전용일 경우 사용
 }
 */
 
 public String regionList(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //액션 및 결과 출력
  RegionDAO dao = new RegionDAO();
  request.setAttribute("list", dao.regionList());
  
  return "WEB-INF/source/RegionList.jsp";
 }
 
 public String regionInsert(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //액션 전용
  //데이터 수신(한글 인코딩 추가)
  request.setCharacterEncoding("UTF-8");
  String regionName = request.getParameter("regionName");

  //데이터베이스 액션 -> add() 메소드 호출로 대체
  RegionDAO dao = new RegionDAO();
  Region r = new Region();
  r.setRegionName(regionName);
  dao.add(r);
  return "redirect:RegionList.it";
 }
 
 public String regionDelete(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //액션 전용
  //데이터 수신(한글 인코딩 추가)
  request.setCharacterEncoding("UTF-8");
  String regionId = request.getParameter("regionId");

  //데이터베이스 액션 -> add() 메소드 호출로 대체
  RegionDAO dao = new RegionDAO();
  dao.remove(regionId);
  
  return "redirect:RegionList.it";
 }
 
 public String regionUpdate(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //액션 전용
  //데이터 수신(한글 인코딩 추가)
  request.setCharacterEncoding("UTF-8");
  String regionName = request.getParameter("regionName");
  String regionId = request.getParameter("regionId");
  
  //데이터베이스 액션 -> add() 메소드 호출로 대체
  RegionDAO dao = new RegionDAO();
  Region r = new Region();
  r.setRegionName(regionName);
  r.setRegionId(regionId);
  dao.modify(r);
  
  return "redirect:RegionList.it";
 }

 public String positionList(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //액션 및 결과 출력
  PositionDAO dao = new PositionDAO();
  request.setAttribute("list", dao.positionList());
  
  return "WEB-INF/source/PositionList.jsp";
 }
 
 public String positionInsert(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //액션 전용
  //데이터 수신(한글 인코딩 추가)
  request.setCharacterEncoding("UTF-8");
  String positionName = request.getParameter("positionName");
  String minBasicPay = request.getParameter("minBasicPay");
  //데이터베이스 액션 -> add() 메소드 호출로 대체
  PositionDAO dao = new PositionDAO();
  Position p = new Position();
  p.setPositionName(positionName);
  p.setMinBasicPay(Integer.parseInt(minBasicPay));
  dao.add(p);
  return "redirect:PositionList.it";
 }
 
 public String positionDelete(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //액션 전용
  //데이터 수신(한글 인코딩 추가)
  request.setCharacterEncoding("UTF-8");
  String positionId = request.getParameter("positionId");

  //데이터베이스 액션 -> add() 메소드 호출로 대체
  PositionDAO dao = new PositionDAO();
  dao.remove(positionId);
  
  return "redirect:PositionList.it";
 }
 
 public String positionUpdate(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //액션 전용
  //데이터 수신(한글 인코딩 추가)
  request.setCharacterEncoding("UTF-8");
  String positionName = request.getParameter("positionName");
  String positionId = request.getParameter("positionId");
  String minBasicPay = request.getParameter("minBasicPay");
  //데이터베이스 액션 -> add() 메소드 호출로 대체
  PositionDAO dao = new PositionDAO();
  Position p = new Position();
  p.setPositionName(positionName);
  p.setPositionId(positionId);
  p.setMinBasicPay(Integer.parseInt(minBasicPay));
  dao.modify(p);
  
  return "redirect:PositionList.it";
 }

 public String departmentList(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //액션 및 결과 출력
  DepartmentDAO dao = new DepartmentDAO();
  request.setAttribute("list", dao.departmentList());
  
  return "WEB-INF/source/DepartmentList.jsp";
 }
 
 public String departmentInsert(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //액션 전용
  //데이터 수신(한글 인코딩 추가)
  request.setCharacterEncoding("UTF-8");
  String departmentName = request.getParameter("departmentName");

  //데이터베이스 액션 -> add() 메소드 호출로 대체
  DepartmentDAO dao = new DepartmentDAO();
  Department d = new Department();
  d.setDepartmentName(departmentName);
  dao.add(d);
  return "redirect:DepartmentList.it";
 }
 
 public String departmentDelete(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //액션 전용
  //데이터 수신(한글 인코딩 추가)
  request.setCharacterEncoding("UTF-8");
  String departmentId = request.getParameter("departmentId");

  //데이터베이스 액션 -> add() 메소드 호출로 대체
  DepartmentDAO dao = new DepartmentDAO();
  dao.remove(departmentId);
  
  return "redirect:DepartmentList.it";
 }
 
 public String departmentUpdate(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  //액션 전용
  //데이터 수신(한글 인코딩 추가)
  request.setCharacterEncoding("UTF-8");
  String departmentName = request.getParameter("departmentName");
  String departmentId = request.getParameter("departmentId");
  
  //데이터베이스 액션 -> add() 메소드 호출로 대체
  DepartmentDAO dao = new DepartmentDAO();
  Department d = new Department();
  d.setDepartmentName(departmentName);
  d.setDepartmentId(departmentId);
  dao.modify(d);
  
  return "redirect:DepartmentList.it";
 }
}

 

 

 

//DepartmentList.jsp -> 기존 JSP 코드 삭제, JSTL, EL 표현 추가
<%@ 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>직원 관리(Servlet MVC 버전)</title>

<link rel="stylesheet" type="text/css" href="TableStyle.css">
<link rel="stylesheet" type="text/css" href="DivStyle.css">

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
 //부서 입력 액션 -> 부서명 빈 항목 검사
 $("#btnAdd").click(function(){
  if($("#departmentName").val()=="") {
   $("#errorMsg").html("부서명을 입력하세요.");
  } else {
   $("#myForm").attr("action", "DepartmentInsert.it");
   $("#myForm").submit();
  }
 });
 
 //부서 수정 액션 -> 부서번호(기존), 부서명(신규) 빈 항목 검사
 $("#btnModify").click(function(){
  if($("#departmentName").val()=="" || $("#departmentId").val()=="") {
   $("#errorMsg").html("부서번호, 부서명을 입력하세요.");
  } else {
   $("#myForm").attr("action", "DepartmentUpdate.it");
   $("#myForm").submit();
  }
 });
 
 //삭제버튼 액션 추가
 $(".btnDelete").click(function(){
  var text = $(this).parent().parent().find("td:first").text();
  if(confirm(text+"번 부서를 삭제할까요?")){
   /* 요청 주소에서 .jsp 사용 금지 */
   $(location).attr("href","DepartmentDelete.it?departmentId="+text);
  }
 });
});
</script>

</head>
<body>
 <div>
  <!-- 메뉴 영역 -->
  <div class="title">
   <h1>직원관리</h1>
   <c:import url="EmployeeMenu.jsp"></c:import>
  </div>

  <!-- 콘텐츠 영역 -->
  <div class="main">
   <h2>부서 관리</h2>
   <form method="post" id="myForm">
    부서번호* <input type="text" name="departmentId" id="departmentId">
    부서명* <input type="text" name="departmentName" id="departmentName">
    
    <input type="button" id="btnAdd" value="부서추가">
    <input type="button" id="btnModify" value="부서수정">
    
    <span id="errorMsg" style="color:red;"></span>
   </form>
   <table id="t01" style="font-size:10pt;">
    <!-- <tr>은 제목 -->
    <tr>
     <th>부서 번호</th>
     <th>부서명</th>
     <th>삭제</th>
    </tr>
    <c:forEach var="d" items="${list}">
    <tr>
     <td>${d.departmentId}</td>
     <td>${d.departmentName}</td>
     <td><input type="button" value="삭제" class="btnDelete"  ${d.delCheck==0?"":"disabled=\"disabled\""}></td>
    </tr>
    </c:forEach>
   </table>
  </div>
 </div>
</body>
</html>

 

 


//PositionList.jsp -> 기존 JSP 코드 삭제, JSTL, EL 표현 추가

<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>직원 관리(Servlet MVC 버전)</title>

<link rel="stylesheet" type="text/css" href="TableStyle.css">
<link rel="stylesheet" type="text/css" href="DivStyle.css">

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
 //직위 추가 액션 -> 직위명, 최소기본급 빈 항목 검사
 $("#btnAdd").click(function(){
  if($("#positionName").val()==""
    || $("#minBasicPay").val()=="") {
   $("#errorMsg").html("직위명, 최소기본급을 입력하세요.");
  } else {
   $("#myForm").attr("action", "PositionInsert.it");
   $("#myForm").submit();
  }
 });
 
 //직위 수정 액션 -> 직위번호(기존), 직위명(신규), 최소기본급 빈 항목 검사
 $("#btnModify").click(function(){
  if($("#positionName").val()==""
     || $("#positionId").val()==""
     || $("#minBasicPay").val()=="") {
   $("#errorMsg").html("직위번호, 직위명, 최소기본급을 입력하세요.");
  } else {
   $("#myForm").attr("action", "PositionUpdate.it");
   $("#myForm").submit();
  }
 });
 
 //삭제버튼 액션 추가
 $(".btnDelete").click(function(){
  var text = $(this).parent().parent().find("td:first").text();
  if(confirm(text+"번 직위 삭제할까요?")){
   /* 요청 주소에서 .jsp 사용 금지 */
   $(location).attr("href","PositionDelete.it?positionId="+text);
  }
 });
});
</script>

</head>
<body>
 <div>
  <!-- 메뉴 영역 -->
  <div class="title">
   <h1>직원관리</h1>
   <c:import url="EmployeeMenu.jsp"></c:import>
  </div>

  <!-- 콘텐츠 영역 -->
  <div class="main">
   <h2>직위 관리</h2>
   <form method="post" id="myForm">
    직위번호* <input type="text" name="positionId" id="positionId">
    직위명* <input type="text" name="positionName" id="positionName">
    최소기본급*<input type="text" name="minBasicPay" id="minBasicPay">
    
    <input type="button" id="btnAdd" value="직위추가">
    <input type="button" id="btnModify" value="직위수정">
    
    <span id="errorMsg" style="color:red;"></span>
   </form>

   <table id="t01" style="font-size:10pt;">

    <!-- <tr>은 제목 -->
    <tr>
     <th>직위 번호</th>
     <th>직위명</th>
     <th>최소기본급</th>
     <th>삭제</th>
    </tr>
    <c:forEach var="p" items="${list}">
    <tr>
     <td>${p.positionId}</td>
     <td>${p.positionName}</td>
     <td><fmt:formatNumber value="${p.minBasicPay}" groupingUsed="true"></fmt:formatNumber></td>
     <td><input type="button" value="삭제" class="btnDelete"  ${p.delCheck==0?"":"disabled=\"disabled\""}></td>
    </tr>
    </c:forEach>
   </table>
  </div>
 </div>
</body>
</html>

 


-----------------------------------------

 

 


 

블로그 이미지

알 수 없는 사용자

,

---------------------------------------------
MVC 패턴
- 컨트롤러 클래스(서블릿)+액션 클래스(일반)


//web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>SampleProject</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
 
  <!-- 서블릿 주소 등록 -->
  <!-- 
  <servlet>
   <servlet-name>서블릿식별자</servlet-name>
   <servlet-class>패키지이름.컨트롤러클래스</servlet-class>
  </servlet>
  <servlet-mapping>
   <servlet-name>서블릿식별자</servlet-name>
   <url-pattern>*.확장자</url-pattern>
  </servlet-mapping>
  --> 
 
  <servlet>
   <servlet-name>controller</servlet-name>
   <servlet-class>com.test.Controller</servlet-class>
  </servlet>
  <servlet-mapping>
   <servlet-name>controller</servlet-name>
   <url-pattern>*.it</url-pattern>
  </servlet-mapping>


</web-app>

 

 

//Controller.java
package com.test;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

/* 액션 주소(*.it)를 분석하고 처리하는 서블릿 클래스(메인페이지) */
public class Controller extends HttpServlet {

 private static final long serialVersionUID = 1L;

 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  //사용자 정의 메소드 호출 부분 추가
  doGetPost(req, resp);
 }

 @Override
 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  //사용자 정의 메소드 호출 부분 추가
  doGetPost(req, resp);
 }
 
 //사용자 정의 메소드 (doGet, doPost 메소드에 대한 통합 액션)
 private void doGetPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  //액션 주소(*.it) 분석 및 처리 과정 추가
  Action action = new Action();
  
  System.out.println("list() 메소드 호출");
  String result = action.list(request, response);
  
  //forward() 또는 sendRedirect() 메소드 선택
  //forward() -> JSP 페이지 연결
  //sendRedirect() -> 서블릿 주소 연결
  RequestDispatcher dispatcher = request.getRequestDispatcher(result);
  dispatcher.forward(request, response);
  
 }
 

}

 

 

//Action.java
package com.test;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

/* 액션 처리 담당 클래스 -> 메소드 단위 */
public class Action {

 //액션 처리 메소드
 public String list(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  System.out.println("list() 메소드 실행");
  
  String msg = "Hello, Servlet world!";
  
  //JSP 페이지(XXXX.jsp) 또는 서블릿 주소(redirect:XXXX.it)
  request.setAttribute("msg", msg);
  return "Sample.jsp";
 }
 

}

 

 

//Sample.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>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

</head>
<body>
<div>
${msg}
</div>
</body>
</html>

 


//요청주소
http://localhost:8090/프로젝트이름/Sample.it

 

---------------------------------------------
회원관리 Servlet(JDBC) 프로그램(5)
-> MVC 패턴
-> 자료형 클래스(자바빈) 및 데이터베이스 액션, 컨트롤러 클래스(서블릿)+액션 클래스(일반), JSP 페이지, web.xml

1. 기능 구현
- 이름, 전화번호 입력 받아서 데이터베이스 저장
- 이름, 전화번호를 데이터베이스에서 읽어내서 화면에 출력

2. 데이터베이스 준비
--테이블 생성
CREATE TABLE memberList (
 mid NUMBER  --PK
 ,name NVARCHAR2(30) --한글 저장
 ,telephone VARCHAR2(30)
);

--제약 조건 추가
ALTER TABLE 테이블이름
 ADD CONSTRAINT 제약이름 제약종류(제약대상);
ALTER TABLE 테이블이름
 DROP CONSTRAINT 제약이름;

ALTER TABLE memberList
 ADD CONSTRAINT memberList_mid_pk PRIMARY KEY(mid);

CREATE SEQUENCE memberListSeq;

--입력 샘플 쿼리 (프로그램에서 사용 예정)
INSERT INTO memberList (mid, name, telephone) VALUES (memberListSeq.nextval, 'kim', '010-123-1234');
COMMIT;

--권장하지 않는 표현. 컬럼 리스트에서 * 사용하지 않는다.
SELECT * FROM memberList;

--전체 명단 출력 쿼리 (프로그램에서 사용 예정)
--권장하는 표현
SELECT mid, name, telephone FROM memberList ORDER BY mid;

--인원수 출력 쿼리 (프로그램에서 사용 예정)
--함수 사용시 반드시 별칭 사용.
SELECT COUNT(mid) AS count FROM memberList;


3. 화면 구성
-----------------------------------------------------------
[회원 관리]

이름 : hong             -> <input type="text">
전화 : 010-123-1234     -> <input type="text">
회원추가버튼                -> <input type="submit">

전체 인원수 : 2명              -> <p> ... </p>
----------------------------   -> <table>...</table>
번호 이름 전화
1   hong   010-123-1234
2   kim    010-222-2222
----------------------------


4. 프로그램 구성
//DBConn.java
//Member.java -> 자료형 클래스
//MemberDAO.java -> 데이터베이스 액션 처리. 메소드 단위로 액션 처리.

//web.xml -> 서블릿 주소 등록. 액션 주소를 확장자(.it)로 표기.

//MemberController.java -> 서블릿 클래스. 액션 주소 처리.
//MemberAction.java -> 일반 클래스. 액션을 메소드 단위로 처리.

//MemberList.jsp -> 회원 명단 출력. 회원 추가 폼 화면. 출력 액션.

//요청주소 (JSP 페이지 요청하지 않는다. 서블릿 주소로 요청한다)
http://localhost:8090/프로젝트이름/MemberList.it


5. 프로그램 소스 코드
//DBConn.java
//Member.java -> 자료형 클래스
//MemberDAO.java -> 데이터베이스 액션 처리. 메소드 단위로 액션 처리.

//web.xml -> 서블릿 주소 등록. 액션 주소를 확장자(.it)로 표기.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>SampleProject</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
 
  <!-- 서블릿 주소 등록 -->
  <!-- 
  <servlet>
   <servlet-name>서블릿식별자</servlet-name>
   <servlet-class>패키지이름.컨트롤러클래스</servlet-class>
  </servlet>
  <servlet-mapping>
   <servlet-name>서블릿식별자</servlet-name>
   <url-pattern>*.확장자</url-pattern>
  </servlet-mapping>
  --> 
 
  <servlet>
   <servlet-name>controller</servlet-name>
   <servlet-class>com.test.MemberController</servlet-class>
  </servlet>
  <servlet-mapping>
   <servlet-name>controller</servlet-name>
   <url-pattern>*.it</url-pattern>
  </servlet-mapping>


</web-app>

 

 


//MemberController.java -> 서블릿 클래스. 액션 주소 처리.
package com.test;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

/* 액션 주소(*.it)를 분석하고 처리하는 서블릿 클래스(메인페이지) */
public class MemberController extends HttpServlet {

 private static final long serialVersionUID = 1L;

 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  //사용자 정의 메소드 호출 부분 추가
  doGetPost(req, resp);
 }

 @Override
 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  //사용자 정의 메소드 호출 부분 추가
  doGetPost(req, resp);
 }
 
 //사용자 정의 메소드 (doGet, doPost 메소드에 대한 통합 액션)
 private void doGetPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  //액션 주소(*.it) 분석 및 처리 과정 추가
  String uri = request.getRequestURI();
  //->"http://localhost:8090/프로젝트이름/Sample.it"

  //액션 담당 클래스의 객체 생성
  MemberAction action = new MemberAction();
  String result = "Error.jsp";
  
  //요청 주소 분석 및 액션 메소드 호출
  if (uri.indexOf("MemberList.it") != -1) {
   //요청주소에 'MemberList.it'가 포함된 경우
   result = action.memberList(request, response);
  }
  if (uri.indexOf("MemberInsert.it") != -1) {
   //요청주소에 'MemberInsert.it'가 포함된 경우
   result = action.memberInsert(request, response);
  }

  if (result.indexOf("redirect:") != -1) {
   //sendRedirect 요청
   response.sendRedirect(result.substring(9));
  } else {
   //forward 요청
   RequestDispatcher dispatcher = request.getRequestDispatcher(result);
   dispatcher.forward(request, response);
  }
  
 }
 

}

 

 

 

//MemberAction.java -> 일반 클래스. 액션을 메소드 단위로 처리.
package com.test;

import java.io.*;
import java.util.ArrayList;

import javax.servlet.*;
import javax.servlet.http.*;

/* 액션 처리 담당 클래스 -> 메소드 단위 */
public class MemberAction {

 /*
 public String 메소드이름(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  return "요청주소";
 }
 */
 public String memberList(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  //데이터베이스 액션
  MemberDAO dao = new MemberDAO();
  int count = dao.count();
  ArrayList<Member> list = dao.list();  
  
  //JSP 페이지 연결->forward() 메소드 연결 예정
  request.setAttribute("count", count);
  request.setAttribute("list", list);  
  return "MemberList.jsp";
 }
 
 public String memberInsert(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  //데이터 수신 (한글 인코딩)
  request.setCharacterEncoding("UTF-8");
  String name = request.getParameter("name");
  String telephone = request.getParameter("telephone");
  
  //데이터베이스 액션
  MemberDAO dao = new MemberDAO();
  Member member = new Member();
  member.setName(name);
  member.setTelephone(telephone);
  dao.add(member);
  
  //강제 페이지 전환 -> sendRedirect() 메소드 연결 예정
  return "redirect:MemberList.it";
 }
  
}

 

 

 

//MemberList.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>회원관리</title>

<link rel="stylesheet" type="text/css" href="MyTable.css">

<style type="text/css">
 #error { display: none; color: red; }
</style>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
 $("#myForm").submit(function() {
  $("#error").css("display", "none");
  if ($("#name").val()=="" || $("#telephone").val()=="") {
   $("#error").css("display", "inline");
   return false;
  }
  return true;
 });
 $("#name").keyup(function(){
  $("#nameLength").html($(this).val().length);
 });
 $("#telephone").keyup(function(){
  $("#telephoneLength").html($(this).val().length);
 });
});
</script>

</head>
<body>
<div>
<h1>[회원 관리]</h1>

<%-- action="" 속성에서 서블릿 주소 지정 (*.it) --%>
<form action="MemberInsert.it" method="post" id="myForm">
 <table>
  <tr>
   <th>이름*</th>
   <td>
   <input type="text" id="name" name="name"
     required="required"> ( <span id="nameLength">0</span> / 30 )
   </td>
  </tr>
  <tr>
   <th>전화*</th>
   <td>
   <input type="text" id="telephone" name="telephone"
     required="required"> ( <span id="telephoneLength">0</span> / 30 )
   </td>
  </tr>
  <tr>
   <th></th>
   <td>
   <input type="submit">
   <span id="error">모든 항목을 채워야 합니다.</span>
   </td>
  </tr>
 </table>
</form>

<h2>
 전체 인원수 : ${count} 명
</h2>
<table id="customers">
 <tr>
  <th>번호</th><th>이름</th><th>전화</th>
 </tr>
 <c:forEach var="member" items="${list}">
 <tr>
  <td>${member.mid}</td>
  <td>${member.name}</td>
  <td>${member.telephone}</td>
 </tr> 
 </c:forEach>
</table>

</div>
</body>
</html>

 

 

//Error.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>회원관리</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

</head>
<body>
<div>
 <div style="margin:auto; padding-top: 100px; width:400px; text-align: center;">
  <img src="txt_error_msg404.gif"><br>
  <a href="MemberList.it">메인 화면으로 가기</a>
 </div>
</div>
</body>
</html>

 


//요청주소 (JSP 페이지 요청하지 않는다. 서블릿 주소로 요청한다)
http://localhost:8090/프로젝트이름/MemberList.it

 


----------------------------------------------
성적관리 Servlet 프로그램(4)
-> MVC 패턴 (Model2)
-> 자료형 클래스 및 데이터베이스 액션, 컨트롤러 클래스+액션 클래스, 화면구성 페이지 분리

 


1. 기능 구현
- 학생 테이블에는 학생의 개인 정보(번호, 학생 이름, 전화번호)가 저장된다.
- 성적 테이블에는 학생의 성적 정보(번호, 과목1, 과목2, 과목3)가 저장된다.
- 번호 항목은 학생 테이블의 PK, 성적 테이블의 PK&FK로 지정한다.
- 학생 출력시 번호, 학생 이름, 전화번호, 성적 입력 여부가 출력된다.
- 학생 입력은 학생 이름, 전화번호를 입력한다.
- 성적 출력시 번호, 학생이름, 과목1, 과목2, 과목3, 총점, 평균, 판정 점수가 출력한다.
- 판정 기준은 합격, 과락, 불합격으로 구분한다.
- 성적 입력이 안된 학생인 경우는 번호, 학생 이름만 출력하고 점수는 null 문자 또는 X 문자로 출력한다.
- 성적 입력은 학생 개개인별로 과목1, 과목2, 과목3 점수를 입력한다.
- 학생 삭제 기능, 성적 삭제 기능 추가

 


2. 화면 구성
---------------------------------------------------
학생명단버튼  성적출력버튼

--- 학생 명단 ---

학생추가버튼

전체 학생 수 : 2명
-----------------------------------------
번호, 학생 이름, 전화번호, 성적 입력 여부, 삭제
-----------------------------------------
1, kim, 010-111-1111, O, 삭제버튼(비활성)
2, park, 010-222-2222, O, 삭제버튼(비활성)
3, choi, 010-456-4567, X,  삭제버튼(활성)

---------------------------------------------------
학생명단버튼  성적출력버튼

--- 학생 추가 ---

이름  [            ]
전화번호 [            ]

학생추가버튼

 

---------------------------------------------------
학생명단버튼  성적출력버튼

--- 성적 출력 ---

전체 학생 수 : 2명
-----------------------------------------
번호, 학생이름, 과목1, 과목2, 과목3, 총점, 평균, 판정, 삭제
-----------------------------------------
1, kim, 100, 100, 100, 300, 100.0, 합격  성적추가버튼(비활성) 삭제버튼(활성)
2, park, 50, 50, 50, 150, 50.0, 불합격  성적추가버튼(비활성) 삭제버튼(활성)
3, choi, null, null, null, null, 0, 불합격   성적추가버튼(활성) 삭제버튼(비활성)

---------------------------------------------------
학생명단버튼  성적출력버튼

--성적 추가--

번호* [3         ]
학생이름* [choi      ]
과목1(0~100) [           ]
과목2(0~100) [           ]
과목3(0~100) [           ]

성적추가버튼


3. 데이터베이스 준비

-- 학생 테이블 생성
CREATE TABLE student (
 sid NUMBER --PK
 ,name NVARCHAR2(30) --한글 저장
 ,tel VARCHAR2(30)
);

--PK 제약 추가
ALTER TABLE student
 ADD CONSTRAINT student_sid_pk PRIMARY KEY(sid);

--일련번호 생성을 위한 시퀀스 객체 생성
CREATE SEQUENCE studentSeq;

--INSERT 쿼리 샘플 (프로그램 사용 예정)
INSERT INTO student (sid, name, tel)
 VALUES (studentSeq.nextval, 'kim', '010-111-1111');
INSERT INTO student (sid, name, tel)
 VALUES (studentSeq.nextval, 'park', '010-222-2222');

SELECT * FROM student;

COMMIT;


--성적 테이블 생성
CREATE TABLE grade (
 sid NUMBER --PK and FK
 ,sub1 NUMBER(3) --CHECK 제약 추가
 ,sub2 NUMBER(3) --CHECK 제약 추가
 ,sub3 NUMBER(3) --CHECK 제약 추가
);

--제약 추가
ALTER TABLE grade
  ADD (CONSTRAINT grade_sid_pk PRIMARY KEY(sid)
        , CONSTRAINT grade_sub1_ck CHECK (sub1 BETWEEN 0 AND 100)
        , CONSTRAINT grade_sub2_ck CHECK (sub2 BETWEEN 0 AND 100)   
        , CONSTRAINT grade_sub3_ck CHECK (sub3 BETWEEN 0 AND 100));

ALTER TABLE grade
  ADD CONSTRAINT grade_sid_fk FOREIGN KEY (sid)
              REFERENCES student(sid);

SELECT *
  FROM constraint_check
  WHERE table_name='GRADE';


--INSERT 쿼리 샘플 (프로그램에서 사용 예정)
INSERT INTO grade (sid, sub1, sub2, sub3)
 VALUES (1, 100, 100, 100); --O
COMMIT;


--학생 테이블의 자료 2명으로 만들 것.
SELECT * FROM student;

--성적 테이블의 자료 1명으로 만들 것.
SELECT * FROM grade;


--학생수 출력 쿼리
SELECT COUNT(*) AS count FROM student;


--학생 전체 명단 출력 쿼리 (프로그램에서 사용 예정)
--번호, 학생 이름, 전화번호, 성적 입력 여부(0 또는 1)
--학생 테이블 + 성적 테이블 -> JOIN, SUB QUERY
--OUTER JOIN의 경우
SELECT s.sid AS sid, name, tel
  , DECODE(sub1, NULL, 0, 1) AS sub  --성적 입력 여부 (1 또는 0)
  FROM student s, grade g
  WHERE s.sid = g.sid(+);

--SUB QUERY의 경우
SELECT sid, name, tel
 , DECODE((SELECT sid FROM grade WHERE sid=s.sid)
  , null, 0, 1) AS sub
 FROM student s;

-->뷰(View)로 등록하는 것을 권장
CREATE OR REPLACE VIEW studentView
AS
SELECT sid, name, tel
 , DECODE((SELECT sid FROM grade WHERE sid=s.sid)
  , null, 0, 1) AS sub
 FROM student s;
-->뷰를 이용한 학생 전체 명단  출력 쿼리
SELECT sid, name, tel, sub
 FROM studentView
 ORDER BY sid;


--학생 검색 쿼리(성적 입력 전에 학생 정보 검색 과정에서 사용. 프로그램에서 사용 예정)
SELECT sid, name, tel, sub
 FROM studentView
 WHERE sid=1;


--성적 출력 쿼리 (프로그램에서 사용 예정)
--번호, 학생이름, 과목1, 과목2, 과목3, 총점, 평균, 판정(0 합격, 1 과락, 2 불합격)
--학생 테이블->번호, 학생이름
--성적 테이블->과목1, 과목2, 과목3
--총점, 평균, 판정 -> 계산 결과
--학생 테이블 + 성적 테이블 -> JOIN, SUB QUERY

주의) 오라클에서 NULL 데이터는 자바에서는 String 자료형인 경우에만 처리 가능.
NUMBER -> int -> 숫자 서식 지정 가능
VARCHAR2 -> String -> 문자열 서식 지정 가능
NUMBER + NULL -> String -> NULL이 아닌 경우에만 Integer.parseInt(String) 가능
VARCHAR2 + NULL -> String

--OUTER JOIN의 경우
SELECT sid, name, sub1, sub2, sub3, tot, ave 
    , ( CASE
          WHEN ave>=60 AND sub1>=40 AND sub2>=40 AND sub3>=40 THEN 0 --합격
          WHEN ave>=60 THEN 1 --과락
          ELSE 2 --불합격
      END ) AS ch
FROM (SELECT s.sid AS sid, name, sub1, sub2, sub3
    , (sub1 + sub2 + sub3) AS tot
    , ( (sub1 + sub2 + sub3) / 3 ) AS ave
  FROM student s, grade g
  WHERE s.sid = g.sid(+));


--> 뷰(View) 등록
CREATE OR REPLACE VIEW gradeView
AS
SELECT sid, name, sub1, sub2, sub3, tot, ave 
    , ( CASE
          WHEN ave>=60 AND sub1>=40 AND sub2>=40 AND sub3>=40 THEN 0 --합격
          WHEN ave>=60 THEN 1 --과락
          ELSE 2 --불합격
      END ) AS ch
FROM (SELECT s.sid AS sid, name, sub1, sub2, sub3
    , (sub1 + sub2 + sub3) AS tot
    , ( (sub1 + sub2 + sub3) / 3 ) AS ave
  FROM student s, grade g
  WHERE s.sid = g.sid(+));

--> 뷰를 이용한 성적 출력
SELECT sid, name, sub1, sub2, sub3, tot, ave, ch
 FROM gradeView
 ORDER BY sid;


--학생 삭제 쿼리
DELETE FROM student WHERE sid=1;

--성적 삭제 쿼리
DELETE FROM grade WHERE sid=1;


4. 프로그램 구성
//DBConn.java
//Student.java -> 자료형 클래스
//Grade.java -> 자료형 클래스
//StudentDAO.java -> 데이터베이스 액션
//GradeDAO.java -> 데이터베이스 액션

//Controller.java -> 서블릿 클래스. 요청 주소 분석.
//Action.java -> 액션 클래스. 액션 메소드 추가.

//StudentMain.jsp -> 학생 명단 출력 페이지. JSTL&EL 표현. 삭제 버튼 추가.
//StudentInsertForm.jsp -> 학생 입력 폼 페이지. action="서블릿주소"
//GradeMain.jsp -> 성적 출력 페이지. JSTL&EL 표현. 삭제 버튼 추가
//GradeInsertForm.jsp -> 성적 입력 폼 페이지. JSTL&EL 표현. action="서블릿주소"

//Error.jsp -> 요청 주소가 잘못되었습니다.

//web.xml -> 서블릿 주소 등록. 확장자 .it 주소 등록.

//요청주소
http://localhost:8090/프로젝트이름/StudentMain.it

5. 프로그램 소스 코드
//DBConn.java
package com.test;

import java.sql.*;

public class DBConn {

 //Connection(데이터베이스 연결) 객체 저장용 변수 선언
 private static Connection conn = null;
 
 //1. 데이터베이스 연결 과정
 public static Connection getConn()
   throws ClassNotFoundException, SQLException {

  //Connection 객체가 생성되지 않은 경우에만
  //신규 객체를 생성한다. -> SingleTone
  if (conn == null) {
   //데이터베이스 연결 액션(로그인 과정)
   Class.forName("oracle.jdbc.driver.OracleDriver");
   String url = "jdbc:oracle:thin:아이디/패스워드@211.63.89.XX:1521:xe";
   conn = DriverManager.getConnection(url);
  }
    
  return conn;
 }
 
 
 //2. 데이터베이스 연결 종료 과정
 public static void close() throws SQLException {
  if (conn != null) {
   conn.close();
  }
  conn = null; //멤버변수를 NULL 값으로 초기화
 }
 
 
}

 


//Student.java -> 자료형 클래스
package com.test;

public class Student {
 
 private int sub;
 private String sid, name, tel;

 public int getSub() {
  return sub;
 }
 public void setSub(int sub) {
  this.sub = sub;
 }
 public String getSid() {
  return sid;
 }
 public void setSid(String sid) {
  this.sid = sid;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getTel() {
  return tel;
 }
 public void setTel(String tel) {
  this.tel = tel;
 }

}

 

 


//Grade.java -> 자료형 클래스
package com.test;

public class Grade {
 
 private int ch;
 private String sid, name, sub1, sub2, sub3, tot, ave;
 
 public int getCh() {
  return ch;
 }
 public void setCh(int ch) {
  this.ch = ch;
 }
 public String getSid() {
  return sid;
 }
 public void setSid(String sid) {
  this.sid = sid;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getSub1() {
  return sub1;
 }
 public void setSub1(String sub1) {
  this.sub1 = sub1;
 }
 public String getSub2() {
  return sub2;
 }
 public void setSub2(String sub2) {
  this.sub2 = sub2;
 }
 public String getSub3() {
  return sub3;
 }
 public void setSub3(String sub3) {
  this.sub3 = sub3;
 }
 public String getTot() {
  return tot;
 }
 public void setTot(String tot) {
  this.tot = tot;
 }
 public String getAve() {
  return ave;
 }
 public void setAve(String ave) {
  this.ave = ave;
 }
 
}

 

 


//StudentDAO.java -> 데이터베이스 액션
package com.test;

import java.sql.*;
import java.util.*;

public class StudentDAO {

 public ArrayList<Student> list() {
  ArrayList<Student> result = new ArrayList<Student>();

  Connection conn = null;
  PreparedStatement pstmt = null;
  try {
   // Connection 객체 얻는 방법
   conn = DBConn.getConn();

   String sql = "SELECT sid, name, tel, sub FROM studentView ORDER BY sid";
   pstmt = conn.prepareStatement(sql);
   ResultSet rs = pstmt.executeQuery();

   while (rs.next()) {
    Student student = new Student();
    student.setSid(rs.getString("sid"));
    student.setName(rs.getString("name"));
    student.setTel(rs.getString("tel"));
    student.setSub(rs.getInt("sub"));
    result.add(student);
   }

   rs.close();

  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   try {
    if (pstmt != null) {
     pstmt.close();
    }
    // 연결 종료시 conn.close(); 사용하면 안됨.
    DBConn.close();
   } catch (Exception e) {
    e.printStackTrace();
   }
  }

  return result;
 }

 public int count() {
  int result = 0;

  Connection conn = null;
  PreparedStatement pstmt = null;
  try {
   // Connection 객체 얻는 방법
   conn = DBConn.getConn();

   String sql = "SELECT COUNT(*) AS count FROM studentView";
   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();
    }
    // 연결 종료시 conn.close(); 사용하면 안됨.
    DBConn.close();
   } catch (Exception e) {
    e.printStackTrace();
   }
  }

  return result;
 }

 public int add(Student student) {

  int result = 0;

  Connection conn = null;
  PreparedStatement pstmt = null;
  try {
   conn = DBConn.getConn();

   String sql = "INSERT INTO student (sid, name, tel) VALUES (studentSeq.nextval, ?, ?)";
   pstmt = conn.prepareStatement(sql);
   pstmt.setString(1, student.getName());
   pstmt.setString(2, student.getTel());
   pstmt.executeUpdate();

  } catch (SQLException e) {
   e.printStackTrace();
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  } finally {
   try {
    if (pstmt != null) {
     pstmt.close();
    }
    DBConn.close();
   } catch (SQLException se) {
    se.printStackTrace();
   }
  }

  return result;
 }

}

 

 


//GradeDAO.java -> 데이터베이스 액션
package com.test;

import java.sql.*;
import java.util.*;

public class GradeDAO {
 public int count() {
  int result = 0;

  Connection conn = null;
  PreparedStatement pstmt = null;
  try {
   conn = DBConn.getConn();

   String sql = "SELECT COUNT(*) AS count FROM studentView";

   pstmt = conn.prepareStatement(sql);
   ResultSet rs = pstmt.executeQuery();
   while (rs.next()) {
    result = rs.getInt("count");
   }
   rs.close();

  } catch (SQLException e) {
   e.printStackTrace();
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  } finally {
   try {
    if (pstmt != null) {
     pstmt.close();
    }
    DBConn.close();
   } catch (SQLException se) {
    se.printStackTrace();
   }
  }
  return result;
 }

 public ArrayList<Grade> list() {
  ArrayList<Grade> result = new ArrayList<Grade>();

  Connection conn = null;
  PreparedStatement pstmt = null;
  try {
   conn = DBConn.getConn();

   String sql = "SELECT sid, name, sub1, sub2, sub3, tot, ave, ch FROM gradeView ORDER BY sid";

   pstmt = conn.prepareStatement(sql);
   ResultSet rs = pstmt.executeQuery();
   while (rs.next()) {
    Grade grade = new Grade();
    grade.setSid(rs.getString("sid"));
    grade.setName(rs.getString("name"));
    grade.setSub1(rs.getString("sub1"));
    grade.setSub2(rs.getString("sub2"));
    grade.setSub3(rs.getString("sub3"));
    grade.setTot(rs.getString("tot"));
    grade.setAve(rs.getString("ave"));
    grade.setCh(rs.getInt("ch"));
    result.add(grade);

   }
   rs.close();

  } catch (SQLException e) {
   e.printStackTrace();
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  } finally {
   try {
    if (pstmt != null) {
     pstmt.close();
    }
    DBConn.close();
   } catch (SQLException se) {
    se.printStackTrace();
   }
  }

  return result;
 }

 public String searchId(String sid) {
  String result = "";

  Connection conn = null;
  PreparedStatement pstmt = null;

  try {
   conn = DBConn.getConn();
   String sql = "SELECT name FROM studentView WHERE sid =?";

   pstmt = conn.prepareStatement(sql);
   pstmt.setInt(1, Integer.parseInt(sid));
   ResultSet rs = pstmt.executeQuery();
   while (rs.next()) {
    result = rs.getString("name");
   }
   rs.close();

  } catch (SQLException e) {
   e.printStackTrace();
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  } finally {
   try {
    if (pstmt != null) {
     pstmt.close();
    }
    DBConn.close();
   } catch (SQLException se) {
    se.printStackTrace();
   }
  }

  return result;
 }

 public int add(Grade grade) {
  int result = 0;

  Connection conn = null;
  PreparedStatement pstmt = null;
  try {
   conn = DBConn.getConn();
   String sql = "INSERT INTO grade (sid, sub1, sub2, sub3) VALUES (?, ?, ?, ?)";

   pstmt = conn.prepareStatement(sql);
   pstmt.setString(1, grade.getSid());
   pstmt.setString(2, grade.getSub1());
   pstmt.setString(3, grade.getSub2());
   pstmt.setString(4, grade.getSub3());
   pstmt.executeUpdate();

  } catch (SQLException e) {
   e.printStackTrace();
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  } finally {
   try {
    if (pstmt != null) {
     pstmt.close();
    }
    DBConn.close();
   } catch (SQLException se) {
    se.printStackTrace();
   }
  }
  return result;
 }
}


------------------------------------------
팀별과제) 성적관리 서블릿 프로그램 소스 코드 작성. MVC 패턴 적용.

//Controller.java -> 서블릿 클래스. 요청 주소 분석.
//Action.java -> 액션 클래스. 액션 메소드 추가.

//StudentList.jsp -> 학생 명단 출력 페이지. JSTL&EL 표현. 삭제 버튼 추가.
//StudentInsertForm.jsp -> 학생 입력 폼 페이지. action="서블릿주소"
//GradeList.jsp -> 성적 출력 페이지. JSTL&EL 표현. 삭제 버튼 추가
//GradeInsertForm.jsp -> 성적 입력 폼 페이지. JSTL&EL 표현. action="서블릿주소"

//Error.jsp -> 요청 주소가 잘못되었습니다.

//web.xml -> 서블릿 주소 등록. 확장자 .it 주소 등록.

//요청주소
http://localhost:8090/프로젝트이름/StudentList.it


-----------------------------------------------

//Controller.java -> 서블릿 클래스. 요청 주소 분석.
package com.test;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

public class Controller extends HttpServlet {

 private static final long serialVersionUID = 1L;

 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  //사용자 정의 메소드 호출 부분 추가
  doGetPost(req, resp);
 }

 @Override
 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  //사용자 정의 메소드 호출 부분 추가
  doGetPost(req, resp);
 }
 
 //사용자 정의 메소드 (doGet, doPost 메소드에 대한 통합 액션)
 private void doGetPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  //액션 주소(*.it) 분석 및 처리 과정 추가
  String uri = request.getRequestURI();
  String result = "Error.jsp";
  
  /*
  액션클래스 action = new 액션클래스();
  if (uri.indexOf("요청주소.it") != -1) {
   result = action.요청메소드(request, response);
  }
  */
  Action action = new Action();
  if (uri.indexOf("StudentList.it") != -1) {
   result = action.studentList(request, response);
  }
  if (uri.indexOf("StudentInsertForm.it") != -1) {
   result = action.studentInsertForm(request, response);
  }
  if (uri.indexOf("StudentInsert.it") != -1) {
   result = action.studentInsert(request, response);
  }
  if (uri.indexOf("StudentDelete.it") != -1) {
   result = action.studentDelete(request, response);
  }
  if (uri.indexOf("GradeList.it") != -1) {
   result = action.gradeList(request, response);
  }
  if (uri.indexOf("GradeInsertForm.it") != -1) {
   result = action.gradeInsertForm(request, response);
  }
  if (uri.indexOf("GradeInsert.it") != -1) {
   result = action.gradeInsert(request, response);
  }
  if (uri.indexOf("GradeDelete.it") != -1) {
   result = action.gradeDelete(request, response);
  }
  
  
  if (result.indexOf("redirect:") != -1) {
   //sendRedirect 요청
   response.sendRedirect(result.substring(9));
  } else {
   //forward 요청
   RequestDispatcher dispatcher = request.getRequestDispatcher(result);
   dispatcher.forward(request, response);
  }  
  
 }
 

}

 

 


//Action.java -> 액션 클래스. 액션 메소드 추가.
package com.test;

import java.io.*;
import java.util.ArrayList;

import javax.servlet.*;
import javax.servlet.http.*;

public class Action {

 /*
 public String 메소드이름(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  return "요청주소";
 }
 */
 public String studentList(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  StudentDAO dao = new StudentDAO();
  int count = dao.count();
  ArrayList<Student> list = dao.list();  
  
  request.setAttribute("count", count);
  request.setAttribute("list", list); 
  return "StudentList.jsp";
 }


 public String studentInsertForm(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  return "StudentInsertForm.jsp";
 }

 public String studentInsert(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  request.setCharacterEncoding("UTF-8");
  String name = request.getParameter("name");
  String tel = request.getParameter("tel");

  StudentDAO dao = new StudentDAO();
  Student student = new Student();
  student.setName(name);
  student.setTel(tel);
  dao.add(student);  
  
  return "redirect:StudentList.it";
 }

 public String studentDelete(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  String sid = request.getParameter("sid");
  
  StudentDAO dao = new StudentDAO();
  dao.remove(sid);
  
  return "redirect:StudentList.it";
 }

 public String gradeList(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  GradeDAO dao = new GradeDAO();
  int count = dao.count();
  ArrayList<Grade> list = dao.list(); 
  for (Grade grade : list) {
   grade.setGrade(studentGrade(grade.getCh()));
  }
  
  request.setAttribute("count", count);
  request.setAttribute("list", list);
  
  return "GradeList.jsp";
 }

 public String gradeInsertForm(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  String sid = request.getParameter("sid");

  GradeDAO dao = new GradeDAO();
  String name = dao.searchId(sid);
  
  request.setAttribute("sid", sid);
  request.setAttribute("name", name);
  
  return "GradeInsertForm.jsp";
 }

 public String gradeInsert(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  String sid = request.getParameter("sid");
  String sub1 = request.getParameter("sub1");
  String sub2 = request.getParameter("sub2");
  String sub3 = request.getParameter("sub3");
  
  GradeDAO dao = new GradeDAO();
  Grade grade = new Grade();
  grade.setSid(sid);
  grade.setSub1(sub1);
  grade.setSub2(sub2);
  grade.setSub3(sub3);
  dao.add(grade);
  
  return "redirect:GradeList.it";
 }

 public String gradeDelete(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  String sid = request.getParameter("sid");
  
  GradeDAO dao = new GradeDAO();
  dao.remove(sid);
  
  return "redirect:GradeList.it";
 }
 
 private String studentGrade(int ch) {
  String[] array = {"합격", "과락", "불합격"};
  return array[ch];
 }

}

 

 


//StudentList.jsp -> 학생 명단 출력 페이지. JSTL&EL 표현. 삭제 버튼 추가.
<%@ 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>[성적관리]</title>

<link rel="stylesheet" type="text/css" href="MyTable.css">

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {
 $("#student").click(function() {
  $(location).attr("href", "StudentList.it");
 });
 $("#grade").click(function() {
  $(location).attr("href", "GradeList.it");
 });
 $("#studentInsertForm").click(function() {
  $(location).attr("href", "StudentInsertForm.it");
 });
 $(".deleteBtn").click(function() {
  if (confirm("선택한 자료를 삭제할까요?")) {
   $(location).attr("href", "StudentDelete.it?sid="+$(this).val());
  }
 });
});
</script>

</head>
<body>
<div>
 <div id="menu">
  <form>
   <input type="button" value="학생명단" id="student">
   <input type="button" value="성적출력" id="grade">
  </form>
 </div>
 
 <div id="content">
  <h1>[학생명단]</h1>
  <h2>전체 학생수 : ${count}명</h2>
  
  <form>
   <input type="button" value="학생추가" id="studentInsertForm">
  </form>
  
  <table id="customers">
   <tr>
    <th style="width:100px;">번호</th><th>이름</th>
    <th>전화번호</th><th style="width:200px;">성적입력여부</th>
    <th>삭제</th>
   </tr>
   <c:forEach var="student" items="${list}">
   <tr>
    <td>${student.sid}</td>
    <td>${student.name}</td>
    <td>${student.tel}</td>
    <td>${student.sub==0?"X":"O"}</td>
    <td>
    <button value="${student.sid}" class="deleteBtn"
        ${student.sub==0?"":"disabled='disabled'"}>삭제</button>
    </td>
   </tr>
   </c:forEach>
  </table>
 
 </div>
</div>
</body>
</html>

 

 

//StudentInsertForm.jsp -> 학생 입력 폼 페이지. action="서블릿주소"
<%@ 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>[성적관리]</title>
<link rel="stylesheet" type="text/css" href="MyTable.css">

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {
 $("#student").click(function() {
  $(location).attr("href", "StudentList.it");
 });
 $("#grade").click(function() {
  $(location).attr("href", "GradeList.it");
 });
 $("#name").keyup(function(){
  $("#nameLength").html($(this).val().length);
 });
 $("#tel").keyup(function(){
  $("#telLength").html($(this).val().length);
 }); 
 $("#studentInsertForm").submit(function() {
  $("#err").html("");
  if ($("#name").val()=="" || $("#tel").val()=="") {
   $("#err").html("빈 항목을 채워야 합니다.");
   return false;
  }
  return true;
 });
});
</script>

</head>
<body>
<div>
 <div id="menu">
  <form>
   <input type="button" value="학생명단" id="student">
   <input type="button" value="성적출력" id="grade">
  </form>
 </div>
 
 <div id="content">
  <h1>[학생추가]</h1>
  
  <form action="StudentInsert.it" method="post"
    id="studentInsertForm">
  <table>
   <tr>
    <td>이름*</td>
    <td>
    
    <%-- 이름 입력 폼에서 글자 수 출력 위한 <span></span> 엘리먼트 추가 --%>
    <input type="text" id="name" name="name"
      required="required"> ( <span id="nameLength">0</span> / 30 )
      
    </td>
   </tr>
   <tr>
    <td>전화*</td>
    <td>
    
    <%-- 전화 입력 폼에서 글자 수 출력 위한 <span></span> 엘리먼트 추가 --%>
    <input type="text" id="tel" name="tel"
      required="required"> ( <span id="telLength">0</span> / 30 )
      
    </td>
   </tr>
   <tr>
    <td></td>
    <td>
    
    <%-- 학생 추가 폼에 대한 서브밋 버튼 --%>
    <input type="submit" value="학생추가">
    <span id="err"></span>
    
    </td>
   </tr>
  </table>
  </form>
 </div>

</div>
</body>
</html>

 

 

 


//GradeList.jsp -> 성적 출력 페이지. JSTL&EL 표현. 삭제 버튼 추가
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%-- 성적 출력 페이지 --%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>   
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>[성적관리]</title>

<link rel="stylesheet" type="text/css" href="MyTable.css">

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {
 $("#student").click(function() {
  $(location).attr("href", "StudentList.it");
 });
 $("#grade").click(function() {
  $(location).attr("href", "GradeList.it");
 });
 $(".btnInsertForm").click(function() {
  $(location).attr("href", "GradeInsertForm.it?sid="+$(this).val());
 });
 $(".deleteBtn").click(function() {
  if (confirm("선택한 자료를 삭제할까요?")) {
   $(location).attr("href", "GradeDelete.it?sid="+$(this).val());
  }
 }); 
});
</script>

</head>
<body>
<div>
 <div id="menu">
  <form>
   <input type="button" value="학생명단" id="student">
   <input type="button" value="성적출력" id="grade">
  </form>
 </div>
 
 <div id="content">
  <h1>[성적출력]</h1>
  <h2>전체 학생수 : ${count} 명</h2>
  <table id="customers">
   <tr>
    <th>번호</th><th>이름</th>
    <th>과목1</th><th>과목2</th><th>과목3</th>
    <th>총점</th><th>평균</th><th>판정</th>
    <th></th><th></th>
   </tr>
   <c:forEach var="grade" items="${list}">
   <tr>
    <td>${grade.sid}</td>
    <td>${grade.name}</td>
    <td>${empty grade.sub1?"null":grade.sub1}</td>
    <td>${empty grade.sub2?"null":grade.sub2}</td>
    <td>${empty grade.sub3?"null":grade.sub3}</td>
    <td>${empty grade.tot?"null":grade.tot}</td>
    <td><fmt:formatNumber value="${grade.ave}" pattern="#.0" /></td>
    <td>${grade.grade}</td>
    <td>
    <button class="btnInsertForm" value="${grade.sid}"
     ${empty grade.sub1?"":"disabled='disabled'"}>성적추가</button>
    </td>
    <td>
    <button value="${grade.sid}" class="deleteBtn"
        ${empty grade.sub1?"disabled='disabled'":""}>삭제</button>
    </td>
   </tr>
   </c:forEach>
  </table>
 </div>

</div>
</body>
</html>

 

 

 


//GradeInsertForm.jsp -> 성적 입력 폼 페이지. JSTL&EL 표현. action="서블릿주소"
<%@ 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>[성적관리]</title>
<link rel="stylesheet" type="text/css" href="MyTable.css">

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {
 $("#student").click(function() {
  $(location).attr("href", "StudentList.it");
 });
 $("#grade").click(function() {
  $(location).attr("href", "GradeList.it");
 });
 $("#gradeInsertForm").submit(function () {
  $("#err").css("display", "none");
  if ($("#sub1").val() == ""
    || $("#sub1").val().match(/[^0-9]/)
    || (parseInt($("#sub1").val())>100 || parseInt($("#sub1").val())<0)) {
   $("#err").html("0~100사이의 값을 넣어주세요.");
   $("#err").css("display", "inline");
   return false;
  }
  if ($("#sub2").val() == ""
   || $("#sub2").val().match(/[^0-9]/)
   || (parseInt($("#sub2").val())>100 || parseInt($("#sub2").val())<0)) {
   $("#err").html("0~100사이의 값을 넣어주세요.");
   $("#err").css("display", "inline");
   return false;
  }
  if ($("#sub3").val() == ""
   || $("#sub3").val().match(/[^0-9]/)
   || (parseInt($("#sub3").val())>100 || parseInt($("#sub3").val())<0)) {
   $("#err").html("0~100사이의 값을 넣어주세요.");
   $("#err").css("display", "inline");
   return false;
  }
  return true;
 });
});
</script>

</head>
<body>
<div>
 <div id="menu">
  <form>
   <input type="button" value="학생명단" id="student">
   <input type="button" value="성적출력" id="grade">
  </form>
 </div>
 
 <div id="content">
 
  <h1>[성적 입력]</h1>
  <form action="GradeInsert.it" method="post"
    id="gradeInsertForm">
  <table>
   <tr>
    <td>번호*</td>
    <td><input type="text" id="sid" name="sid"
      value="${sid}" readonly="readonly" ></td>
   </tr>
   <tr>
    <td>이름*</td>
    <td><input type="text" id="name" name="name"
      value="${name}" readonly="readonly" ></td>
   </tr>
   <tr>
    <td>sub1*</td>
    <td><input type="text" id="sub1" name="sub1"
      required="required"> </td>
   </tr>
   <tr>
    <td>sub2*</td>
    <td><input type="text" id="sub2" name="sub2"
      required="required"> </td>
   </tr>
   <tr>
    <td>sub3*</td>
    <td><input type="text" id="sub3" name="sub3"
      required="required"> </td>
   </tr>
   <tr>
    <td></td>
    <td>
    <input type="submit" value="성적추가">
    <span id="err"></span>
    </td>
   </tr>
  </table>

  </form>
 
 </div>

</div>
</body>
</html>

 

 

//Error.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>성적관리</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

</head>
<body>
<div>
 <div style="margin:auto; padding-top: 100px; width:400px; text-align: center;">
  <img src="txt_error_msg404.gif"><br>
  <a href="StudentList.it">메인 화면으로 가기</a>
 </div>
</div>
</body>
</html>

 

 

//web.xml -> 서블릿 주소 등록. 확장자 .it 주소 등록.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>SampleProject</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
 
  <!-- 서블릿 주소 등록 -->
  <!-- 
  <servlet>
   <servlet-name>서블릿식별자</servlet-name>
   <servlet-class>패키지이름.컨트롤러클래스</servlet-class>
  </servlet>
  <servlet-mapping>
   <servlet-name>서블릿식별자</servlet-name>
   <url-pattern>*.확장자</url-pattern>
  </servlet-mapping>
  --> 

  <servlet>
   <servlet-name>controller</servlet-name>
   <servlet-class>com.test.Controller</servlet-class>
  </servlet>
  <servlet-mapping>
   <servlet-name>controller</servlet-name>
   <url-pattern>*.it</url-pattern>
  </servlet-mapping>
   
</web-app>

 


//요청주소
http://localhost:8090/프로젝트이름/StudentList.it

------------------------------------------------

 


 

 

'MVC' 카테고리의 다른 글

07일차_MVC패턴, 직원관리  (0) 2015.06.30
06일차_MVC패턴, 직원관리  (0) 2015.06.30
05일차_MVC패턴, 직원관리  (0) 2015.06.30
03일차(2)_모델2방식, 성적관리  (0) 2015.06.30
03일차_MVC패턴, 회원관리, 성적관리  (0) 2015.06.30
블로그 이미지

알 수 없는 사용자

,

----------------------------------------------
성적관리 Servlet 프로그램(3)
-> Model2 방식
-> 자료형 클래스 및 데이터베이스 액션, 서블릿 클래스, 화면구성 페이지 분리

 

1. 기능 구현
- 학생 테이블에는 학생의 개인 정보(번호, 학생 이름, 전화번호)가 저장된다.
- 성적 테이블에는 학생의 성적 정보(번호, 과목1, 과목2, 과목3)가 저장된다.
- 번호 항목은 학생 테이블의 PK, 성적 테이블의 PK&FK로 지정한다.
- 학생 출력시 번호, 학생 이름, 전화번호, 성적 입력 여부가 출력된다.
- 학생 입력은 학생 이름, 전화번호를 입력한다.
- 성적 출력시 번호, 학생이름, 과목1, 과목2, 과목3, 총점, 평균, 판정 점수가 출력한다.
- 판정 기준은 합격, 과락, 불합격으로 구분한다.
- 성적 입력이 안된 학생인 경우는 번호, 학생 이름만 출력하고 점수는 null 문자 또는 X 문자로 출력한다.
- 성적 입력은 학생 개개인별로 과목1, 과목2, 과목3 점수를 입력한다.
- 학생 삭제 기능, 성적 삭제 기능 추가


2. 화면 구성
---------------------------------------------------
학생명단버튼  성적출력버튼

--- 학생 명단 ---

학생추가버튼

전체 학생 수 : 2명
-----------------------------------------
번호, 학생 이름, 전화번호, 성적 입력 여부, 삭제
-----------------------------------------
1, kim, 010-111-1111, O, 삭제버튼(비활성)
2, park, 010-222-2222, O, 삭제버튼(비활성)
3, choi, 010-456-4567, X,  삭제버튼(활성)

---------------------------------------------------
학생명단버튼  성적출력버튼

--- 학생 추가 ---

이름  [            ]
전화번호 [            ]

학생추가버튼

 

---------------------------------------------------
학생명단버튼  성적출력버튼

--- 성적 출력 ---

전체 학생 수 : 2명
-----------------------------------------
번호, 학생이름, 과목1, 과목2, 과목3, 총점, 평균, 판정, 삭제
-----------------------------------------
1, kim, 100, 100, 100, 300, 100.0, 합격  성적추가버튼(비활성) 삭제버튼(활성)
2, park, 50, 50, 50, 150, 50.0, 불합격  성적추가버튼(비활성) 삭제버튼(활성)
3, choi, null, null, null, null, 0, 불합격   성적추가버튼(활성) 삭제버튼(비활성)

---------------------------------------------------
학생명단버튼  성적출력버튼

--성적 추가--

번호* [3         ]
학생이름* [choi      ]
과목1(0~100) [           ]
과목2(0~100) [           ]
과목3(0~100) [           ]

성적추가버튼


3. 데이터베이스 준비

-- 학생 테이블 생성
CREATE TABLE student (
 sid NUMBER --PK
 ,name NVARCHAR2(30) --한글 저장
 ,tel VARCHAR2(30)
);

--PK 제약 추가
ALTER TABLE student
 ADD CONSTRAINT student_sid_pk PRIMARY KEY(sid);

--일련번호 생성을 위한 시퀀스 객체 생성
CREATE SEQUENCE studentSeq;

--INSERT 쿼리 샘플 (프로그램 사용 예정)
INSERT INTO student (sid, name, tel)
 VALUES (studentSeq.nextval, 'kim', '010-111-1111');
INSERT INTO student (sid, name, tel)
 VALUES (studentSeq.nextval, 'park', '010-222-2222');

SELECT * FROM student;

COMMIT;


--성적 테이블 생성
CREATE TABLE grade (
 sid NUMBER --PK and FK
 ,sub1 NUMBER(3) --CHECK 제약 추가
 ,sub2 NUMBER(3) --CHECK 제약 추가
 ,sub3 NUMBER(3) --CHECK 제약 추가
);

--제약 추가
ALTER TABLE grade
  ADD (CONSTRAINT grade_sid_pk PRIMARY KEY(sid)
        , CONSTRAINT grade_sub1_ck CHECK (sub1 BETWEEN 0 AND 100)
        , CONSTRAINT grade_sub2_ck CHECK (sub2 BETWEEN 0 AND 100)   
        , CONSTRAINT grade_sub3_ck CHECK (sub3 BETWEEN 0 AND 100));

ALTER TABLE grade
  ADD CONSTRAINT grade_sid_fk FOREIGN KEY (sid)
              REFERENCES student(sid);

SELECT *
  FROM constraint_check
  WHERE table_name='GRADE';


--INSERT 쿼리 샘플 (프로그램에서 사용 예정)
INSERT INTO grade (sid, sub1, sub2, sub3)
 VALUES (1, 100, 100, 100); --O
COMMIT;


--학생 테이블의 자료 2명으로 만들 것.
SELECT * FROM student;

--성적 테이블의 자료 1명으로 만들 것.
SELECT * FROM grade;


--학생수 출력 쿼리
SELECT COUNT(*) AS count FROM student;


--학생 전체 명단 출력 쿼리 (프로그램에서 사용 예정)
--번호, 학생 이름, 전화번호, 성적 입력 여부(0 또는 1)
--학생 테이블 + 성적 테이블 -> JOIN, SUB QUERY
--OUTER JOIN의 경우
SELECT s.sid AS sid, name, tel
  , DECODE(sub1, NULL, 0, 1) AS sub  --성적 입력 여부 (1 또는 0)
  FROM student s, grade g
  WHERE s.sid = g.sid(+);

--SUB QUERY의 경우
SELECT sid, name, tel
 , DECODE((SELECT sid FROM grade WHERE sid=s.sid)
  , null, 0, 1) AS sub
 FROM student s;

-->뷰(View)로 등록하는 것을 권장
CREATE OR REPLACE VIEW studentView
AS
SELECT sid, name, tel
 , DECODE((SELECT sid FROM grade WHERE sid=s.sid)
  , null, 0, 1) AS sub
 FROM student s;
-->뷰를 이용한 학생 전체 명단  출력 쿼리
SELECT sid, name, tel, sub
 FROM studentView
 ORDER BY sid;


--학생 검색 쿼리(성적 입력 전에 학생 정보 검색 과정에서 사용. 프로그램에서 사용 예정)
SELECT sid, name, tel, sub
 FROM studentView
 WHERE sid=1;


--성적 출력 쿼리 (프로그램에서 사용 예정)
--번호, 학생이름, 과목1, 과목2, 과목3, 총점, 평균, 판정(0 합격, 1 과락, 2 불합격)
--학생 테이블->번호, 학생이름
--성적 테이블->과목1, 과목2, 과목3
--총점, 평균, 판정 -> 계산 결과
--학생 테이블 + 성적 테이블 -> JOIN, SUB QUERY

주의) 오라클에서 NULL 데이터는 자바에서는 String 자료형인 경우에만 처리 가능.
NUMBER -> int -> 숫자 서식 지정 가능
VARCHAR2 -> String -> 문자열 서식 지정 가능
NUMBER + NULL -> String -> NULL이 아닌 경우에만 Integer.parseInt(String) 가능
VARCHAR2 + NULL -> String

--OUTER JOIN의 경우
SELECT sid, name, sub1, sub2, sub3, tot, ave 
    , ( CASE
          WHEN ave>=60 AND sub1>=40 AND sub2>=40 AND sub3>=40 THEN 0 --합격
          WHEN ave>=60 THEN 1 --과락
          ELSE 2 --불합격
      END ) AS ch
FROM (SELECT s.sid AS sid, name, sub1, sub2, sub3
    , (sub1 + sub2 + sub3) AS tot
    , ( (sub1 + sub2 + sub3) / 3 ) AS ave
  FROM student s, grade g
  WHERE s.sid = g.sid(+));


--> 뷰(View) 등록
CREATE OR REPLACE VIEW gradeView
AS
SELECT sid, name, sub1, sub2, sub3, tot, ave 
    , ( CASE
          WHEN ave>=60 AND sub1>=40 AND sub2>=40 AND sub3>=40 THEN 0 --합격
          WHEN ave>=60 THEN 1 --과락
          ELSE 2 --불합격
      END ) AS ch
FROM (SELECT s.sid AS sid, name, sub1, sub2, sub3
    , (sub1 + sub2 + sub3) AS tot
    , ( (sub1 + sub2 + sub3) / 3 ) AS ave
  FROM student s, grade g
  WHERE s.sid = g.sid(+));

--> 뷰를 이용한 성적 출력
SELECT sid, name, sub1, sub2, sub3, tot, ave, ch
 FROM gradeView
 ORDER BY sid;


--학생 삭제 쿼리
DELETE FROM student WHERE sid=1;

--성적 삭제 쿼리
DELETE FROM grade WHERE sid=1;


4. 프로그램 구성
//DBConn.java
//Student.java -> 자료형 클래스
//Grade.java -> 자료형 클래스
//StudentDAO.java -> 데이터베이스 액션
//GradeDAO.java -> 데이터베이스 액션

//StudentMain.java -> 서블릿 클래스. 학생 명단 출력 액션 처리. 메인 페이지. forward() 메소드.
//StudentMain.jsp -> 학생 명단 출력 페이지. JSTL&EL 표현. 삭제 버튼 추가.

//StudentInsertForm.java -> 서블릿 클래스. forward() 메소드.
//StudentInsertForm.jsp -> 학생 입력 폼 페이지. action="서블릿주소"

//StudentInsert.java -> 서블릿 클래스. 학생 입력 액션 처리. 액션 전용. sendRedirect() 메소드.

//StudentDelete.java -> 서블릿 클래스. 학생 삭제 액션 처리. 액션 전용. sendRedirect() 메소드.

//GradeMain.java -> 서블릿 클래스. 성적 출력 액션 처리. forward() 메소드
//GradeMain.jsp -> 성적 출력 페이지. JSTL&EL 표현. 삭제 버튼 추가

//GradeInsertForm.java -> 서블릿 클래스. forward() 메소드.
//GradeInsertForm.jsp -> 성적 입력 폼 페이지. JSTL&EL 표현. action="서블릿주소"

//GradeInsert.java -> 서블릿 클래스. 성적 입력 액션 처리. 액션 전용. sendRedirect() 메솓.

//GradeDelete.java -> 서블릿 클래스. 성적 삭제 액션 처리. 액션 전용. sendRedirect() 메솓.

//web.xml -> 서블릿 주소 등록

//요청주소
http://localhost:8090/프로젝트이름/StudentMain


5. 프로그램 소스 코드
//DBConn.java
package com.test;

import java.sql.*;

public class DBConn {

 //Connection(데이터베이스 연결) 객체 저장용 변수 선언
 private static Connection conn = null;
 
 //1. 데이터베이스 연결 과정
 public static Connection getConn()
   throws ClassNotFoundException, SQLException {

  //Connection 객체가 생성되지 않은 경우에만
  //신규 객체를 생성한다. -> SingleTone
  if (conn == null) {
   //데이터베이스 연결 액션(로그인 과정)
   Class.forName("oracle.jdbc.driver.OracleDriver");
   String url = "jdbc:oracle:thin:아이디/패스워드@211.63.89.XX:1521:xe";
   conn = DriverManager.getConnection(url);
  }
    
  return conn;
 }
 
 
 //2. 데이터베이스 연결 종료 과정
 public static void close() throws SQLException {
  if (conn != null) {
   conn.close();
  }
  conn = null; //멤버변수를 NULL 값으로 초기화
 }
 
 
}

 


//Student.java -> 자료형 클래스
package com.test;

public class Student {
 
 private int sub;
 private String sid, name, tel;

 public int getSub() {
  return sub;
 }
 public void setSub(int sub) {
  this.sub = sub;
 }
 public String getSid() {
  return sid;
 }
 public void setSid(String sid) {
  this.sid = sid;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getTel() {
  return tel;
 }
 public void setTel(String tel) {
  this.tel = tel;
 }

}

 

 


//Grade.java -> 자료형 클래스
package com.test;

public class Grade {
 
 private int ch;
 private String sid, name, sub1, sub2, sub3, tot, ave;
 
 public int getCh() {
  return ch;
 }
 public void setCh(int ch) {
  this.ch = ch;
 }
 public String getSid() {
  return sid;
 }
 public void setSid(String sid) {
  this.sid = sid;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getSub1() {
  return sub1;
 }
 public void setSub1(String sub1) {
  this.sub1 = sub1;
 }
 public String getSub2() {
  return sub2;
 }
 public void setSub2(String sub2) {
  this.sub2 = sub2;
 }
 public String getSub3() {
  return sub3;
 }
 public void setSub3(String sub3) {
  this.sub3 = sub3;
 }
 public String getTot() {
  return tot;
 }
 public void setTot(String tot) {
  this.tot = tot;
 }
 public String getAve() {
  return ave;
 }
 public void setAve(String ave) {
  this.ave = ave;
 }
 
}

 

 


//StudentDAO.java -> 데이터베이스 액션
package com.test;

import java.util.*;
import java.sql.*;

public class StudentDAO {

 //학생 명단 출력 메소드
 public ArrayList<Student> list() {
  ArrayList<Student> result = new  ArrayList<Student>();
  
  //1. 데이터베이스 연결
  //2. SELECT 쿼리 준비 및 실행
  //3. 결과를 컬렉션에 저장
  //4. 데이터베이스 연결 마무리
  //5. 컬렉션 반환
  
  Connection conn = null;
  Statement stmt = null;
  try {
   conn = DBConn.getConnection();

   stmt = conn.createStatement();
   //주의: 쿼리 문자열 끝에 ;(semicolon) 없음.
   String sql = String.format("SELECT sid, name, tel, gradeCheck  FROM studentView  ORDER BY sid");
   ResultSet rs = stmt.executeQuery(sql);
   
   while(rs.next()) {
    //문제)
    //데이터베이스 자료를 순차적으로 읽어내서
    //Student 객체에 저장하고
    //Student 객체를 컬렉션에 저장하는 액션 추가
    String sid = rs.getString("sid");
    String name = rs.getString("name");
    String tel = rs.getString("tel");
    int gradeCheck = rs.getInt("gradeCheck");
      
    Student s = new Student();
    s.setSid(sid);
    s.setName(name);
    s.setTel(tel);
    s.setGradeCheck(gradeCheck);
    
    result.add(s);

   }
   
   rs.close();
   
  }catch(Exception e){
   e.printStackTrace();
  }finally{
   try {
    if (stmt != null) {
     stmt.close();
    }
   }catch(Exception e){
   }
   DBConn.close();
  }
  
  return result;
 }
 
 //학생 수 출력 메소드
 public int count() {
  int result = 0;
  
  //1. 데이터베이스 연결
  //2. SELECT 쿼리 준비 및 실행
  //->SELECT COUNT(*) AS "count" FROM student
  //3. 결과를 변수에 저장
  //4. 데이터베이스 연결 마무리
  //5. 변수 반환  
  
  Connection conn = null;
  PreparedStatement pstmt = null;
  try {
   conn = DBConn.getConnection();  
   
   String sql = String.format("SELECT COUNT(*) AS \"count\" FROM student");

   pstmt = conn.prepareStatement(sql);
   //바인딩 데이터 연결하는 과정
   ResultSet rs = pstmt.executeQuery(); //SELECT 쿼리인 경우
   
   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(Student student) {
  int result = 0;
  
  //문제)
  //1. 데이터베이스 연결
  //2. INSERT 쿼리 준비 및 실행
  //-> INSERT INTO student (sid, name, tel)
  //      VALUES (studentSeq.nextval, ?, ?)
  //3. 결과를 변수에 저장
  //4. 데이터베이스 연결 마무리
  //5. 변수 반환   
  
  Connection conn = null;
  PreparedStatement pstmt = null;
  try {
   conn = DBConn.getConnection(); 
  
   String sql = String.format("INSERT INTO student (sid, name, tel) VALUES (studentSeq.nextval, ?, ?)");
   pstmt = conn.prepareStatement(sql); //쿼리를 사전 분석한다.
   
   pstmt.setString(1, student.getName()); //'(작은 따옴표) 추가
   pstmt.setString(2, student.getTel()); //'(작은 따옴표) 추가
   result = pstmt.executeUpdate();
   
  }catch(Exception e){
   e.printStackTrace();
  }finally{
   try {
    if (pstmt != null) {
     pstmt.close();
    }
   }catch(Exception e){
   }
   
   DBConn.close();   
  }
  
  return result;
 }
 
 
 
 //학생 번호 검색 메소드
 public Student searchSid(String sid) {
  
  Student result = null;
  
  //문제)
  //1. 데이터베이스 연결
  //2. SELECT 쿼리 준비 및 실행
  //SELECT sid, name, tel, gradeCheck
  //     FROM studentView
  //     WHERE sid=?
  //3. 결과를 변수에 저장
  //4. 데이터베이스 연결 마무리
  //5. 변수 반환  
  
  Connection conn = null;
  PreparedStatement pstmt = null;
  try {
   conn = DBConn.getConnection();  
   
   //검색 액션은 PK 가 지정된 sid 컬럼을 대상으로
   //하기 때문에
   //검색 결과는 0 또는 1 이다.
   //검색 결과가 있다면 Student 객체에 저장해서 반환.
   
   String sql = String.format("SELECT sid, name, tel, gradeCheck FROM studentView WHERE sid=?");
   
   pstmt = conn.prepareStatement(sql);
   //바인딩 데이터 연결하는 과정
   pstmt.setInt(1, Integer.parseInt(sid));
   ResultSet rs = pstmt.executeQuery(); //SELECT 쿼리인 경우
   
   //SELECT 결과가 존재하는 경우
   //rs.next() 메소드 결과는 true가 된다.
   //-> 반복문 실행 가능
   /*
   while(rs.next()) {
    result = new Student();
    
   }
    */ 
   while(rs.next()) {
    
    String name = rs.getString("name");
    String tel = rs.getString("tel");
    int gradeCheck = rs.getInt("gradeCheck");
    
    result = new Student();
    result.setSid(sid);
    result.setName(name);
    result.setTel(tel);
    result.setGradeCheck(gradeCheck);

   }
  
   rs.close();
  
  }catch(Exception e){
   e.printStackTrace();
  }finally{
   try {
    if (pstmt != null) {
     pstmt.close();
    }
   }catch(Exception e){
   }
   
   DBConn.close();   
  }  

  return result;  //null 또는 Student객체
  
 }
 
 
 
 //학생 삭제 메소드
 public int remove(String sid) {
  int result = 0;
  
  Connection conn = null;
  PreparedStatement pstmt = null;
  try {
   conn = DBConn.getConnection();  
  
   //DELETE FROM studentView WHERE sid=?
   String sql = String.format("DELETE FROM studentView WHERE sid=?");
   pstmt = conn.prepareStatement(sql);
   pstmt.setString(1, sid);
   result = pstmt.executeUpdate();
  
  }catch(Exception e){
   e.printStackTrace();
  }finally{
   try {
    if (pstmt != null) {
     pstmt.close();
    }
   }catch(Exception e){
   }
   
   DBConn.close();   
  }
  
  return result;
 }
 
  
 
}

 

 

//GradeDAO.java -> 데이터베이스 액션
package com.test;

import java.sql.*;
import java.util.*;

public class GradeDAO {
 public int count() {
  int result = 0;

  Connection conn = null;
  PreparedStatement pstmt = null;
  try {
   conn = DBConn.getConn();

   String sql = "SELECT COUNT(*) AS count FROM studentView";

   pstmt = conn.prepareStatement(sql);
   ResultSet rs = pstmt.executeQuery();
   while (rs.next()) {
    result = rs.getInt("count");
   }
   rs.close();

  } catch (SQLException e) {
   e.printStackTrace();
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  } finally {
   try {
    if (pstmt != null) {
     pstmt.close();
    }
    DBConn.close();
   } catch (SQLException se) {
    se.printStackTrace();
   }
  }
  return result;
 }

 public ArrayList<Grade> list() {
  ArrayList<Grade> result = new ArrayList<Grade>();

  Connection conn = null;
  PreparedStatement pstmt = null;
  try {
   conn = DBConn.getConn();

   String sql = "SELECT sid, name, sub1, sub2, sub3, tot, ave, ch FROM gradeView ORDER BY sid";

   pstmt = conn.prepareStatement(sql);
   ResultSet rs = pstmt.executeQuery();
   while (rs.next()) {
    Grade grade = new Grade();
    grade.setSid(rs.getString("sid"));
    grade.setName(rs.getString("name"));
    grade.setSub1(rs.getString("sub1"));
    grade.setSub2(rs.getString("sub2"));
    grade.setSub3(rs.getString("sub3"));
    grade.setTot(rs.getString("tot"));
    grade.setAve(rs.getString("ave"));
    grade.setCh(rs.getInt("ch"));
    result.add(grade);

   }
   rs.close();

  } catch (SQLException e) {
   e.printStackTrace();
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  } finally {
   try {
    if (pstmt != null) {
     pstmt.close();
    }
    DBConn.close();
   } catch (SQLException se) {
    se.printStackTrace();
   }
  }

  return result;
 }

 public String searchId(String sid) {
  String result = "";

  Connection conn = null;
  PreparedStatement pstmt = null;

  try {
   conn = DBConn.getConn();
   String sql = "SELECT name FROM studentView WHERE sid =?";

   pstmt = conn.prepareStatement(sql);
   pstmt.setInt(1, Integer.parseInt(sid));
   ResultSet rs = pstmt.executeQuery();
   while (rs.next()) {
    result = rs.getString("name");
   }
   rs.close();

  } catch (SQLException e) {
   e.printStackTrace();
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  } finally {
   try {
    if (pstmt != null) {
     pstmt.close();
    }
    DBConn.close();
   } catch (SQLException se) {
    se.printStackTrace();
   }
  }

  return result;
 }

 public int add(Grade grade) {
  int result = 0;

  Connection conn = null;
  PreparedStatement pstmt = null;
  try {
   conn = DBConn.getConn();
   String sql = "INSERT INTO grade (sid, sub1, sub2, sub3) VALUES (?, ?, ?, ?)";

   pstmt = conn.prepareStatement(sql);
   pstmt.setString(1, grade.getSid());
   pstmt.setString(2, grade.getSub1());
   pstmt.setString(3, grade.getSub2());
   pstmt.setString(4, grade.getSub3());
   pstmt.executeUpdate();

  } catch (SQLException e) {
   e.printStackTrace();
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  } finally {
   try {
    if (pstmt != null) {
     pstmt.close();
    }
    DBConn.close();
   } catch (SQLException se) {
    se.printStackTrace();
   }
  }
  return result;
 }
}

 


//StudentMain.java -> 서블릿 클래스. 학생 명단 출력 액션 처리. 메인 페이지. forward() 메소드.
package com.test;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.*;
import javax.servlet.http.*;

public class StudentMain extends HttpServlet {

 private static final long serialVersionUID = 1L;

 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  doGetPost(req, resp);
 }

 @Override
 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  doGetPost(req, resp);
 }
 
 private void doGetPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  //데이터베이스 액션
  StudentDAO dao = new StudentDAO();
  int count = dao.count();
  ArrayList<Student> list = dao.list();

  //결과 전달 및 페이지 전환
  request.setAttribute("count", count);
  request.setAttribute("list", list);
  RequestDispatcher dispatcher
   = request.getRequestDispatcher("StudentMain.jsp");
  dispatcher.forward(request, response);
 }
 
 
}

 

 

//StudentMain.jsp -> 학생 명단 출력 페이지. JSTL&EL 표현
<%@ 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>성적관리</title>

<link rel="stylesheet" type="text/css" href="TableStyle.css">
<link rel="stylesheet" type="text/css" href="DivStyle.css">

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {
 $("#btnAdd").click(function() {
  /* 요청주소에서 .jsp 사용 금지 */
  $(location).attr("href", "StudentInsertForm");
 });
 
 $(".btnDelete").click(function() {
  var sid = $(this).parent().parent().find("td:first").text();
  if (confirm(sid+"번 학생을 삭제할까요?")){
   /* 요청주소에서 .jsp 사용 금지 */
   $(location).attr("href", "StudentDelete?sid="+sid);
  }
 });
 
});
</script>

</head>
<body>
 <div>
  <%-- 메인 메뉴 영역 --%>
  <div class="title">
   <h1>성적관리(Servlet버전)</h1>
   <p>
    <!-- 요청주소에서 .jsp 사용 금지 -->
    <a href="StudentMain">[학생관리]</a>
    <a href="GradeMain">[성적관리]</a>
   </p>
  </div>
  <%-- 콘텐츠 영역 --%>
  <div class="main">
   <h2>--학생명단--</h2>
   <form>
    <input type="button" value="학생추가"
     id="btnAdd">
   </form>
   <%-- <p>전체 학생 수 : 2명</p> --%>
   <p>전체 학생수 : ${count}명</p>
   <table id="t01" style = "text-align : center;">
    <tr>
     <th style="text-align: center;">번호</th>
     <th>이름</th>
     <th>전화번호</th>
     <th>성적입력여부</th>
     <th>삭제</th>
    </tr>
    <!-- <tr style="text-align: center;">
     <td>1</td>
     <td>Kim gildong</td>
     <td>010-1234-1234</td>
     <td>O</td>
     <td>삭제버튼</td>
    </tr> -->
    
    <c:forEach var="s" items="${list}">
    <tr style="text-align: center;">
     <td>${s.sid}</td>
     <td>${s.name}</td>
     <td>${s.tel}</td>
     <td>${s.gradeCheck==0?"X":"O"}</td>
     <td>
     <!-- 식별자 사용시 id="" 대신 class="" 사용할 것 -->
     <input type="button" value="삭제"
       class="btnDelete" ${s.gradeCheck==0?"":"disabled=\"disabled\""}>
     </td>
    </tr>
    </c:forEach>
    
   </table>
  </div>
 </div>
 
 
 
</body>
</html>

 

 


//StudentInsertForm.java
package com.test;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.*;

public class StudentInsertForm extends HttpServlet {

 private static final long serialVersionUID = 1L;

 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  doGetPost(req, resp);
 }

 @Override
 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  doGetPost(req, resp);
 }
 
 private void doGetPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  //페이지 전환
  RequestDispatcher dispatcher
   = request.getRequestDispatcher("StudentInsertForm.jsp");
  dispatcher.forward(request, response);
 }
  
 

}

 

 


//StudentInsertForm.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>성적관리</title>

<link rel="stylesheet" type="text/css" href="TableStyle.css">
<link rel="stylesheet" type="text/css" href="DivStyle.css">

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script type="text/javascript">
//문제) jQuery 버전 작성

</script>

</head>
<body>
 <div>
  <%-- 메인 메뉴 영역 --%>
  <div class="title">
   <h1>성적관리(JSP버전)</h1>
   <p>
    <!-- 요청주소에서 .jsp 사용 금지 -->
    <a href="StudentMain">[학생관리]</a>
    <a href="GradeMain">[성적관리]</a>
   </p>
  </div>
  <%-- 콘텐츠 영역 --%>
  <div class="main">
   <h2>학생 추가</h2>
   <form>
    <input type="button" value="학생명단"
     id="btnList">
   </form>
   <!-- 요청주소에서 .jsp 사용 금지 -->
   <form action="StudentInsert" method="post" id="myForm">
    <table>
     <tr>
      <th>이름*</th>
      <td style="text-align: left;">
      <input type="text" name="name" id="name">(30자이내)
      <span id="errMsg" style="color: red;"></span>
      </td>
     </tr>
     <tr>
      <th>전화번호</th>
      <td><input type="text" name="tel" id="tel"></td>
     </tr>
     <tr>
      <th></th>
      <td><input type="submit" value="가입"></td>
     </tr>
    </table>
   </form>
  </div>
 </div>
</body>
</html>

 

 

//StudentInsert.java
package com.test;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.*;

public class StudentInsert extends HttpServlet {

 private static final long serialVersionUID = 1L;

 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  doGetPost(req, resp);
 }

 @Override
 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  doGetPost(req, resp);
 }
 
 private void doGetPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  //액션 전용 페이지
  
  //데이터 수신(한글 인코딩 추가)
  request.setCharacterEncoding("UTF-8");
  String name = request.getParameter("name");
  String tel = request.getParameter("tel");
  
  //데이터베이스 액션->add() 메소드 호출
  StudentDAO dao = new StudentDAO();
  Student s = new Student();
  s.setName(name);
  s.setTel(tel);
  dao.add(s);
 
  //서블릿 주소 지정
  response.sendRedirect("StudentMain");
 }
 
 

}

 


//StudentDelete.java
package com.test;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.*;

public class StudentDelete extends HttpServlet {

 private static final long serialVersionUID = 1L;

 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  doGetPost(req, resp);
 }

 @Override
 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  doGetPost(req, resp);
 }
 
 private void doGetPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  //액션 전용 페이지
  
  //데이터 수신
  String sid = request.getParameter("sid");
  
  //데이터베이스 액션
  StudentDAO dao = new StudentDAO();
  dao.remove(sid);
  
  //페이지 전환 (서블릿 주소 지정)
  response.sendRedirect("StudentMain");
  
 }
  
 

}

 

 


//web.xml -> 서블릿 주소 등록
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Temp</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

<!--  
 <servlet>
  <servlet-name></servlet-name>
  <servlet-class></servlet-class>
 </servlet> 
 <servlet-mapping>
  <servlet-name></servlet-name>
  <url-pattern></url-pattern>
 </servlet-mapping>
 -->

 <servlet>
  <servlet-name>studentMain</servlet-name>
  <servlet-class>com.test.StudentMain</servlet-class>
 </servlet> 
 <servlet-mapping>
  <servlet-name>studentMain</servlet-name>
  <url-pattern>/StudentMain</url-pattern>
 </servlet-mapping>
 
  
 <servlet>
  <servlet-name>studentInsertForm</servlet-name>
  <servlet-class>com.test.StudentInsertForm</servlet-class>
 </servlet> 
 <servlet-mapping>
  <servlet-name>studentInsertForm</servlet-name>
  <url-pattern>/StudentInsertForm</url-pattern>
 </servlet-mapping>
 
  
 <servlet>
  <servlet-name>studentInsert</servlet-name>
  <servlet-class>com.test.StudentInsert</servlet-class>
 </servlet> 
 <servlet-mapping>
  <servlet-name>studentInsert</servlet-name>
  <url-pattern>/StudentInsert</url-pattern>
 </servlet-mapping>
 
  
  
 <servlet>
  <servlet-name>studentDelete</servlet-name>
  <servlet-class>com.test.StudentDelete</servlet-class>
 </servlet> 
 <servlet-mapping>
  <servlet-name>studentDelete</servlet-name>
  <url-pattern>/StudentDelete</url-pattern>
 </servlet-mapping>
  
  
</web-app>

 

 

//요청주소
http://localhost:8090/프로젝트이름/StudentMain


----------------------------------------------------
문제) 성적 액션 작성 할 것.
- 성적 출력, 입력, 삭제
- GradeMain.java, GradeMain.jsp
- GradeInsertForm.java, GradeInsertForm.jsp
- GradeInsert.java
- GradeDelete.java
- web.xml


//GradeMain.java
package com.test;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.*;
import javax.servlet.http.*;


public class GradeMain extends HttpServlet {

 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  doGetPost(req, resp);
 }

 @Override
 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  doGetPost(req, resp);
 }

 private void doGetPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  
    GradeDAO dao = new GradeDAO();
    StudentDAO dao2 = new StudentDAO();
    int count = dao2.count();
    ArrayList<Grade> list = dao.list();
   
    request.setAttribute("count", count);
    request.setAttribute("list", list);
  RequestDispatcher disPatcher = request.getRequestDispatcher("GradeMain.jsp");
  disPatcher.forward(request, response);
 }
}

 

 

//GradeMain.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" %>
<%@ taglib prefix="fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %>
 <%--
    StringBuilder sb = new StringBuilder();
    int count = 0;

    GradeDAO dao = new GradeDAO();
 String[] array = {"합격","과락","불합격"};

 //인원수 얻는 과정 추가

    for(Grade g : dao.list()){
     sb.append(String.format("<tr>"));
  sb.append(String.format("<td>%s</td>", g.getSid()));
  sb.append(String.format("<td>%s</td>", g.getName()));
  sb.append(String.format("<td>%s</td>", ((g.getSub1()==null)?"X":g.getSub1())));
  sb.append(String.format("<td>%s</td>", (g.getSub2()==null)?"X":g.getSub2()));
  sb.append(String.format("<td>%s</td>", (g.getSub3()==null)?"X":g.getSub3()));
  sb.append(String.format("<td>%s</td>", (g.getTot()==null)?"X":g.getTot()));
   sb.append(String.format("<td>%s</td>", (g.getAve()==null)?"X":String.format("%.1f", Double.parseDouble(g.getAve()))));
  sb.append(String.format("<td>%s</td>", (array[g.getCh()])));
  sb.append(String.format("<td><input type = \"button\" value =\"성적 추가\" %s onclick = \"location.href = 'GradeInsertForm.jsp?sid=%s'\"></td>"
    ,(g.getSub1()==null)?"":"disabled=\"disabled\"", g.getSid()));
  sb.append(String.format("</tr>"));
    }
   
   
    --%>
   
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel = "stylesheet" type = "text/css" href = "TableStyle.css" >
<link rel = "stylesheet" type = "text/css" href = "DivStyle.css">
<script type="text/javascript">
$(document).ready(function(){
 $(".btnInsert").click(function(){
  var sid = $(this).parent().parent().find("td:first").text();
  $(location).attr("href", "GradeInsertForm?sid="+sid);
  
 });
 $(".btnDelete").click(function(){
  var sid = $(this).parent().parent().find("td:first").text();
  if(confirm(sid+"번 성적을 삭제 하시겠습니까?")){
  $(location).attr("href", "GradeDelete?sid="+sid);
  }
 });
});

</script>
</head>
<body>
<form>
<div>
<!-- 타이틀 영역 -->
<div class = "title">
<h1>성적관리 (JSP버전)</h1>
<p>
<a href = "StudentMain">학생 명단</a>
<a href = "GradeMain">성적 출력</a>
</p>
</div>
<!-- 컨텐츠 영역 -->
<div>
<h2>성적 출력</h2>
<p>전체 학생 수 : ${count} 명</p>
<table id = "t01">
<tr>
<th>번호</th><th>이름</th><th>과목1</th><th>과목2</th><th>과목3</th><th>총점</th><th>평균</th><th>판정</th><th>성적 입력</th><th>성적 삭제</th>
</tr>
<c:forEach var = "g" items ="${list}">
  <tr>
  <td>${g.sid}</td>
  <td>${g.name}</td>
  <td>${g.sub1==null?"X":g.sub1}</td>
  <td>${g.sub2==null?"X":g.sub2}</td>
  <td>${g.sub3==null?"X":g.sub3}</td>
  <td>${g.tot==null?"X":g.tot}</td>
  <%-- <td>${g.ave==null?"X":g.ave}</td> --%>
  <td>
               <c:choose>
                  <c:when test="${g.ave==null}"> X </c:when>
                  <c:when test="${g.ave!=null}"><fmt:formatNumber value="${g.ave}" pattern ="##.#"></fmt:formatNumber> </c:when>
               </c:choose>
        </td>
  <td>
               <c:choose>
                  <c:when test="${g.ch==0}"> 합격</c:when>
                  <c:when test="${g.ch==1}"> 과락</c:when>
                  <c:when test="${g.ch==2}"> 불합격</c:when>
               </c:choose>
        </td>
  <td><input type="button" value = "성적입력" class="btnInsert"
   ${g.sub1==null?"":"disabled=\"disabled\""}
  ></td>
  <td><input type="button" value = "성적삭제" class="btnDelete"
   ${g.sub1==null?"disabled=\"disabled\"":""}
  ></td>
  </tr>
  </c:forEach>
</table>
</div>
</div>
</form>
</body>
</html>

 

 

//GradeInsertForm.java
package com.test;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.*;


public class GradeInsertForm extends HttpServlet {

 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  doGetPost(req, resp);
 }

 @Override
 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  doGetPost(req, resp);
 }

 private void doGetPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
     String sid = request.getParameter("sid");
      String name = "";
      /* select name from studentview where sid = ? */
        
      GradeDAO dao = new GradeDAO();
      name = dao.getName(sid);
  
      request.setAttribute("sid", sid);
      request.setAttribute("name", name);
     
  RequestDispatcher disPatcher = request.getRequestDispatcher("GradeInsertForm.jsp");
  disPatcher.forward(request, response);
 }
}

 

 


//GradeInsertForm.jsp
<%@page import="com.sun.xml.internal.txw2.Document"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import = "com.test.*" %>
<%--
    String sid = request.getParameter("sid");
    String name = "";
    /* select name from studentview where sid = ? */
      
    GradeDAO dao = new GradeDAO();
    name = dao.getName(sid);

  
--%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel = "stylesheet" type = "text/css" href = "TableStyle.css" >
<link rel = "stylesheet" type = "text/css" href = "DivStyle.css">
<script type="text/javascript">
$(document).ready(function(){
 
});
</script>
</head>
<body>
<form>
<div>
<!-- 타이틀 영역 -->
<div class = "title">
<h1>성적관리 (JSP버전)</h1>
<p>
<a href = "StudentMain.jsp">학생 명단</a>
<a href = "GradeMain.jsp">성적 출력</a>
</p>
</div>
</div>
</form>
<!-- 컨텐츠 영역 -->

<div>
<h2>성적 추가</h2>
<form action = "GradeInsert"  method = "post" id ="myForm">
<table class = "t01">
<tr>
<th>번호*</th><td><input type = "text" value ="${sid}" readonly="readonly" name = "sid">ReadOnly</td>
</tr>
<tr>
<th>학생이름*</th><td><input type = "text" value ="${name} " readonly="readonly">ReadOnly</td>
</tr>
<tr>
<th>과목1</th><td><input type = "text" name = "sub1" id = "sub1">(0 ~ 100)</td>
</tr>
<tr>
<th>과목2</th><td><input type = "text" name = "sub2" id = "sub2">(0 ~ 100)</td>
</tr>
<tr>
<th>과목3</th><td><input type = "text" name = "sub3" id = "sub3">(0 ~ 100)</td>
</tr>
<tr>
<th></th>
<td style = "text-align: left; padding-left: 4pc;"><input type = "submit" value = "입력완료" ><span id = "errMsg" style = "color: red;"></td>
</tr>


</table>
</form>
</div>

</body>
</html>

 

 

 

//GradeInsert.java
package com.test;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.*;


public class GradeInsert extends HttpServlet {

 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  doGetPost(req, resp);
 }

 @Override
 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  doGetPost(req, resp);
 }

 private void doGetPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  request.setCharacterEncoding("UTF-8");
     String sid = request.getParameter("sid");
  String sub1 = request.getParameter("sub1");
  String sub2 = request.getParameter("sub2");
  String sub3 = request.getParameter("sub3");
 

    GradeDAO dao = new GradeDAO();
    Grade g = new Grade();
    g.setSid(sid);
    g.setSub1(sub1);
    g.setSub2(sub2);
    g.setSub3(sub3);
    dao.add(g);
    
  
  response.sendRedirect("GradeMain");
 /* RequestDispatcher disPatcher = request.getRequestDispatcher("");
  disPatcher.forward(request, response);*/
 }
}

 

 


//GradeDelete.java
package com.test;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.*;


public class GradeDelete extends HttpServlet {

 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  doGetPost(req, resp);
 }

 @Override
 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  doGetPost(req, resp);
 }

 private void doGetPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  String sid = request.getParameter("sid");
  GradeDAO dao = new GradeDAO();
  dao.remove(sid);
  
  response.sendRedirect("GradeMain");
 /* RequestDispatcher disPatcher = request.getRequestDispatcher("");
  disPatcher.forward(request, response);*/
 }
}

 

 


//web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Servlet_Temp</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
   <servlet-name>StudentMain</servlet-name>
   <servlet-class>com.test.StudentMain</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>StudentMain</servlet-name>
    <url-pattern>/StudentMain</url-pattern>
  </servlet-mapping>
 
    <servlet>
   <servlet-name>StudentInsert</servlet-name>
   <servlet-class>com.test.StudentInsert</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>StudentInsert</servlet-name>
    <url-pattern>/StudentInsert</url-pattern>
  </servlet-mapping>
 
    <servlet>
   <servlet-name>StudentDelete</servlet-name>
   <servlet-class>com.test.StudentDelete</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>StudentDelete</servlet-name>
    <url-pattern>/StudentDelete</url-pattern>
  </servlet-mapping>
  
    <servlet>
   <servlet-name>StudentInsertForm</servlet-name>
   <servlet-class>com.test.StudentInsertForm</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>StudentInsertForm</servlet-name>
    <url-pattern>/StudentInsertForm</url-pattern>
  </servlet-mapping>
 
    <servlet>
   <servlet-name>GradeInsert</servlet-name>
   <servlet-class>com.test.GradeInsert</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>GradeInsert</servlet-name>
    <url-pattern>/GradeInsert</url-pattern>
  </servlet-mapping>
 
    <servlet>
   <servlet-name>GradeInsertForm</servlet-name>
   <servlet-class>com.test.GradeInsertForm</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>GradeInsertForm</servlet-name>
    <url-pattern>/GradeInsertForm</url-pattern>
  </servlet-mapping>
 
     <servlet>
   <servlet-name>GradeMain</servlet-name>
   <servlet-class>com.test.GradeMain</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>GradeMain</servlet-name>
    <url-pattern>/GradeMain</url-pattern>
  </servlet-mapping>
 
       <servlet>
   <servlet-name>GradeDelete</servlet-name>
   <servlet-class>com.test.GradeDelete</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>GradeDelete</servlet-name>
    <url-pattern>/GradeDelete</url-pattern>
  </servlet-mapping>
 
 
</web-app>

 

 


------------------------------------------

 

 

 

 

블로그 이미지

알 수 없는 사용자

,

---------------------------------------------
MVC 패턴
- 컨트롤러 클래스(서블릿)+액션 클래스(일반)


//web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Servlet_temp</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
 
  <!-- 서블릿 주소 등록 -->
  <!--
 <servlet>
  <servlet-name>식별자</servlet-name>
  <servlet-class>서블릿 클래스 이름</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>식별자</servlet-name>
  <url-pattern>요청주소</url-pattern>
 </servlet-mapping>
  --> 
 
 
 <!-- MVC 패턴에서는 web.xml에서 서블릿 대표주소 한 개만 등록한다. -->
 <!-- 대표주소는 확장자(사용자 임의 지정)를 동일하게 지정하게 된다. -->
 <!-- 확장자는 일반적으로 .do를 많이 사용 -->
 
 <!-- Contoller 클래스는 사용자 요청 주소 분석 담당 클래스 -->
 <servlet>
  <servlet-name>controller</servlet-name>
  <servlet-class>com.test.Controller</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>controller</servlet-name>
  <url-pattern>*.it</url-pattern>
 </servlet-mapping> 
 
 
</web-app>

 

 

//Controller.java
package com.test;

import java.io.*;

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 Controller extends HttpServlet {

 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {

  //사용자 정의 메소드 호출 구문 추가
  doGetPost(req, resp);
 
 }

 @Override
 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {

  //사용자 정의 메소드 호출 구문 추가
  doGetPost(req, resp);
 
 }
 
 //사용자 정의 메소드 추가 (통합 액션 처리)
 private void doGetPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  //액션 코드 작성 -> 사용자 요청 주소 분석 액션
  String result = "Error.jsp";

  Action action = new Action();
  
  //사용자 요청 주소 분석 결과에 따라서 다른 메소드 호출
  String uri = request.getRequestURI();
  
  if (uri.indexOf("Hello.it") != -1) {
   result = action.method(request, response);
  }
  
  if (result.indexOf("redirect:") == -1) {
   RequestDispatcher dispatcher
    = request.getRequestDispatcher(result);
   dispatcher.forward(request, response);
  } else {
   response.sendRedirect(result);
  }
  
 }

 
 
 
}

 

 


//Action.java
package com.test;

import java.io.IOException;

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

/* 액션 전용 클래스 */
public class Action {
 
 //사용자 요청에 따른 액션 메소드
 public String method(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  //액션 코드 작성
  String msg = "Hello, Servlet MVC World!";
  
  request.setAttribute("msg", msg);
  
  return "WEB-INF/source/Hello.jsp";
  //return "redirect:요청주소";
 }

}

 

 


//Hello.jsp -> WEB-INF/source 폴더 하위에 작성
<%@ 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>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

</head>
<body>
<div>
${msg}
</div>
</body>
</html>

 


//요청주소
http://localhost:8090/프로젝트이름/Hello.it

 

---------------------------------------------
회원관리 Servlet(JDBC) 프로그램(5)
-> MVC 패턴
-> 자료형 클래스(자바빈) 및 데이터베이스 액션, 컨트롤러 클래스(서블릿)+액션 클래스(일반), JSP 페이지, web.xml

1. 기능 구현
- 이름, 전화번호 입력 받아서 데이터베이스 저장
- 이름, 전화번호를 데이터베이스에서 읽어내서 화면에 출력

2. 데이터베이스 준비
--테이블 생성
CREATE TABLE memberList (
 mid NUMBER  --PK
 ,name NVARCHAR2(30) --한글 저장
 ,telephone VARCHAR2(30)
);

--제약 조건 추가
ALTER TABLE 테이블이름
 ADD CONSTRAINT 제약이름 제약종류(제약대상);
ALTER TABLE 테이블이름
 DROP CONSTRAINT 제약이름;

ALTER TABLE memberList
 ADD CONSTRAINT memberList_mid_pk PRIMARY KEY(mid);

CREATE SEQUENCE memberListSeq;

--입력 샘플 쿼리 (프로그램에서 사용 예정)
INSERT INTO memberList (mid, name, telephone) VALUES (memberListSeq.nextval, 'kim', '010-123-1234');
COMMIT;

--권장하지 않는 표현. 컬럼 리스트에서 * 사용하지 않는다.
SELECT * FROM memberList;

--전체 명단 출력 쿼리 (프로그램에서 사용 예정)
--권장하는 표현
SELECT mid, name, telephone FROM memberList ORDER BY mid;

--인원수 출력 쿼리 (프로그램에서 사용 예정)
--함수 사용시 반드시 별칭 사용.
SELECT COUNT(mid) AS count FROM memberList;


3. 화면 구성
-----------------------------------------------------------
[회원 관리]

이름 : hong             -> <input type="text">
전화 : 010-123-1234     -> <input type="text">
회원추가버튼                -> <input type="submit">

전체 인원수 : 2명              -> <p> ... </p>
----------------------------   -> <table>...</table>
번호 이름 전화
1   hong   010-123-1234
2   kim    010-222-2222
----------------------------


4. 프로그램 구성
//DBConn.java
//Member.java -> 자료형 클래스
//MemberDAO.java -> 데이터베이스 액션 처리. 메소드 단위로 액션 처리.

//web.xml -> 서블릿 주소 등록. 액션 주소를 확장자(.it)로 표기.

//Controller.java -> 서블릿 클래스. 액션 주소 처리.
//Action.java -> 일반 클래스. 액션을 메소드 단위로 처리.

//MemberList.jsp -> 회원 명단 출력. 회원 추가 폼 화면. 출력 액션.

//요청주소 (JSP 페이지 요청하지 않는다. 서블릿 주소로 요청한다)
http://localhost:8090/프로젝트이름/MemberList.it


5. 프로그램 소스 코드
//DBConn.java
//Member.java -> 자료형 클래스
//MemberDAO.java -> 데이터베이스 액션 처리. 메소드 단위로 액션 처리.

//web.xml -> 서블릿 주소 등록. 액션 주소를 확장자(.it)로 표기.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>SampleProject</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
 
  <!-- 서블릿 주소 등록 -->
  <!-- 
  <servlet>
   <servlet-name>서블릿식별자</servlet-name>
   <servlet-class>패키지이름.컨트롤러클래스</servlet-class>
  </servlet>
  <servlet-mapping>
   <servlet-name>서블릿식별자</servlet-name>
   <url-pattern>*.확장자</url-pattern>
  </servlet-mapping>
  --> 
 
  <servlet>
   <servlet-name>controller</servlet-name>
   <servlet-class>com.test.MemberController</servlet-class>
  </servlet>
  <servlet-mapping>
   <servlet-name>controller</servlet-name>
   <url-pattern>*.it</url-pattern>
  </servlet-mapping>


</web-app>

 

 


//Controller.java -> 서블릿 클래스. 액션 주소 처리.
package com.test;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

/* 액션 주소(*.it)를 분석하고 처리하는 서블릿 클래스(메인페이지) */
public class MemberController extends HttpServlet {

 private static final long serialVersionUID = 1L;

 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  //사용자 정의 메소드 호출 부분 추가
  doGetPost(req, resp);
 }

 @Override
 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  //사용자 정의 메소드 호출 부분 추가
  doGetPost(req, resp);
 }
 
 //사용자 정의 메소드 (doGet, doPost 메소드에 대한 통합 액션)
 private void doGetPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  //액션 주소(*.it) 분석 및 처리 과정 추가
  String uri = request.getRequestURI();
  //->"http://localhost:8090/프로젝트이름/Sample.it"

  //액션 담당 클래스의 객체 생성
  MemberAction action = new MemberAction();
  String result = "Error.jsp";
  
  //요청 주소 분석 및 액션 메소드 호출
  if (uri.indexOf("MemberList.it") != -1) {
   //요청주소에 'MemberList.it'가 포함된 경우
   result = action.memberList(request, response);
  }
  if (uri.indexOf("MemberInsert.it") != -1) {
   //요청주소에 'MemberInsert.it'가 포함된 경우
   result = action.memberInsert(request, response);
  }

  if (result.indexOf("redirect:") != -1) {
   //sendRedirect 요청
   response.sendRedirect(result.substring(9));
  } else {
   //forward 요청
   RequestDispatcher dispatcher = request.getRequestDispatcher(result);
   dispatcher.forward(request, response);
  }
  
 }
 

}

 

 

 

//MemberAction.java -> 일반 클래스. 액션을 메소드 단위로 처리.
package com.test;

import java.io.*;
import java.util.ArrayList;

import javax.servlet.*;
import javax.servlet.http.*;

/* 액션 처리 담당 클래스 -> 메소드 단위 */
public class MemberAction {

 /*
 public String 메소드이름(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  return "요청주소";
 }
 */
 public String memberList(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  //데이터베이스 액션
  MemberDAO dao = new MemberDAO();
  int count = dao.count();
  ArrayList<Member> list = dao.list();  
  
  //JSP 페이지 연결->forward() 메소드 연결 예정
  request.setAttribute("count", count);
  request.setAttribute("list", list);  
  return "MemberList.jsp";
 }
 
 public String memberInsert(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  //데이터 수신 (한글 인코딩)
  request.setCharacterEncoding("UTF-8");
  String name = request.getParameter("name");
  String telephone = request.getParameter("telephone");
  
  //데이터베이스 액션
  MemberDAO dao = new MemberDAO();
  Member member = new Member();
  member.setName(name);
  member.setTelephone(telephone);
  dao.add(member);
  
  //강제 페이지 전환 -> sendRedirect() 메소드 연결 예정
  return "redirect:MemberList.it";
 }
  
}

 

 

 

//MemberList.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>회원관리</title>

<link rel="stylesheet" type="text/css" href="MyTable.css">

<style type="text/css">
 #error { display: none; color: red; }
</style>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
 $("#myForm").submit(function() {
  $("#error").css("display", "none");
  if ($("#name").val()=="" || $("#telephone").val()=="") {
   $("#error").css("display", "inline");
   return false;
  }
  return true;
 });
 $("#name").keyup(function(){
  $("#nameLength").html($(this).val().length);
 });
 $("#telephone").keyup(function(){
  $("#telephoneLength").html($(this).val().length);
 });
});
</script>

</head>
<body>
<div>
<h1>[회원 관리]</h1>

<%-- action="" 속성에서 서블릿 주소 지정 (*.it) --%>
<form action="MemberInsert.it" method="post" id="myForm">
 <table>
  <tr>
   <th>이름*</th>
   <td>
   <input type="text" id="name" name="name"
     required="required"> ( <span id="nameLength">0</span> / 30 )
   </td>
  </tr>
  <tr>
   <th>전화*</th>
   <td>
   <input type="text" id="telephone" name="telephone"
     required="required"> ( <span id="telephoneLength">0</span> / 30 )
   </td>
  </tr>
  <tr>
   <th></th>
   <td>
   <input type="submit">
   <span id="error">모든 항목을 채워야 합니다.</span>
   </td>
  </tr>
 </table>
</form>

<h2>
 전체 인원수 : ${count} 명
</h2>
<table id="customers">
 <tr>
  <th>번호</th><th>이름</th><th>전화</th>
 </tr>
 <c:forEach var="member" items="${list}">
 <tr>
  <td>${member.mid}</td>
  <td>${member.name}</td>
  <td>${member.telephone}</td>
 </tr> 
 </c:forEach>
</table>

</div>
</body>
</html>

 

 

//Error.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>회원관리</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

</head>
<body>
<div>
 <div style="margin:auto; padding-top: 100px; width:400px; text-align: center;">
  <img src="txt_error_msg404.gif"><br>
  <a href="MemberList.it">메인 화면으로 가기</a>
 </div>
</div>
</body>
</html>

 


//요청주소 (JSP 페이지 요청하지 않는다. 서블릿 주소로 요청한다)
http://localhost:8090/프로젝트이름/MemberList.it

 


----------------------------------------------
성적관리 Servlet 프로그램(4)
-> MVC 패턴 (Model2)
-> 자료형 클래스 및 데이터베이스 액션, 컨트롤러 클래스+액션 클래스, 화면구성 페이지 분리

 


1. 기능 구현
- 학생 테이블에는 학생의 개인 정보(번호, 학생 이름, 전화번호)가 저장된다.
- 성적 테이블에는 학생의 성적 정보(번호, 과목1, 과목2, 과목3)가 저장된다.
- 번호 항목은 학생 테이블의 PK, 성적 테이블의 PK&FK로 지정한다.
- 학생 출력시 번호, 학생 이름, 전화번호, 성적 입력 여부가 출력된다.
- 학생 입력은 학생 이름, 전화번호를 입력한다.
- 성적 출력시 번호, 학생이름, 과목1, 과목2, 과목3, 총점, 평균, 판정 점수가 출력한다.
- 판정 기준은 합격, 과락, 불합격으로 구분한다.
- 성적 입력이 안된 학생인 경우는 번호, 학생 이름만 출력하고 점수는 null 문자 또는 X 문자로 출력한다.
- 성적 입력은 학생 개개인별로 과목1, 과목2, 과목3 점수를 입력한다.
- 학생 삭제 기능, 성적 삭제 기능 추가

 


2. 화면 구성
---------------------------------------------------
학생명단버튼  성적출력버튼

--- 학생 명단 ---

학생추가버튼

전체 학생 수 : 2명
-----------------------------------------
번호, 학생 이름, 전화번호, 성적 입력 여부, 삭제
-----------------------------------------
1, kim, 010-111-1111, O, 삭제버튼(비활성)
2, park, 010-222-2222, O, 삭제버튼(비활성)
3, choi, 010-456-4567, X,  삭제버튼(활성)

---------------------------------------------------
학생명단버튼  성적출력버튼

--- 학생 추가 ---

이름  [            ]
전화번호 [            ]

학생추가버튼

 

---------------------------------------------------
학생명단버튼  성적출력버튼

--- 성적 출력 ---

전체 학생 수 : 2명
-----------------------------------------
번호, 학생이름, 과목1, 과목2, 과목3, 총점, 평균, 판정, 삭제
-----------------------------------------
1, kim, 100, 100, 100, 300, 100.0, 합격  성적추가버튼(비활성) 삭제버튼(활성)
2, park, 50, 50, 50, 150, 50.0, 불합격  성적추가버튼(비활성) 삭제버튼(활성)
3, choi, null, null, null, null, 0, 불합격   성적추가버튼(활성) 삭제버튼(비활성)

---------------------------------------------------
학생명단버튼  성적출력버튼

--성적 추가--

번호* [3         ]
학생이름* [choi      ]
과목1(0~100) [           ]
과목2(0~100) [           ]
과목3(0~100) [           ]

성적추가버튼


3. 데이터베이스 준비

-- 학생 테이블 생성
CREATE TABLE student (
 sid NUMBER --PK
 ,name NVARCHAR2(30) --한글 저장
 ,tel VARCHAR2(30)
);

--PK 제약 추가
ALTER TABLE student
 ADD CONSTRAINT student_sid_pk PRIMARY KEY(sid);

--일련번호 생성을 위한 시퀀스 객체 생성
CREATE SEQUENCE studentSeq;

--INSERT 쿼리 샘플 (프로그램 사용 예정)
INSERT INTO student (sid, name, tel)
 VALUES (studentSeq.nextval, 'kim', '010-111-1111');
INSERT INTO student (sid, name, tel)
 VALUES (studentSeq.nextval, 'park', '010-222-2222');

SELECT * FROM student;

COMMIT;


--성적 테이블 생성
CREATE TABLE grade (
 sid NUMBER --PK and FK
 ,sub1 NUMBER(3) --CHECK 제약 추가
 ,sub2 NUMBER(3) --CHECK 제약 추가
 ,sub3 NUMBER(3) --CHECK 제약 추가
);

--제약 추가
ALTER TABLE grade
  ADD (CONSTRAINT grade_sid_pk PRIMARY KEY(sid)
        , CONSTRAINT grade_sub1_ck CHECK (sub1 BETWEEN 0 AND 100)
        , CONSTRAINT grade_sub2_ck CHECK (sub2 BETWEEN 0 AND 100)   
        , CONSTRAINT grade_sub3_ck CHECK (sub3 BETWEEN 0 AND 100));

ALTER TABLE grade
  ADD CONSTRAINT grade_sid_fk FOREIGN KEY (sid)
              REFERENCES student(sid);

SELECT *
  FROM constraint_check
  WHERE table_name='GRADE';


--INSERT 쿼리 샘플 (프로그램에서 사용 예정)
INSERT INTO grade (sid, sub1, sub2, sub3)
 VALUES (1, 100, 100, 100); --O
COMMIT;


--학생 테이블의 자료 2명으로 만들 것.
SELECT * FROM student;

--성적 테이블의 자료 1명으로 만들 것.
SELECT * FROM grade;


--학생수 출력 쿼리
SELECT COUNT(*) AS count FROM student;


--학생 전체 명단 출력 쿼리 (프로그램에서 사용 예정)
--번호, 학생 이름, 전화번호, 성적 입력 여부(0 또는 1)
--학생 테이블 + 성적 테이블 -> JOIN, SUB QUERY
--OUTER JOIN의 경우
SELECT s.sid AS sid, name, tel
  , DECODE(sub1, NULL, 0, 1) AS sub  --성적 입력 여부 (1 또는 0)
  FROM student s, grade g
  WHERE s.sid = g.sid(+);

--SUB QUERY의 경우
SELECT sid, name, tel
 , DECODE((SELECT sid FROM grade WHERE sid=s.sid)
  , null, 0, 1) AS sub
 FROM student s;

-->뷰(View)로 등록하는 것을 권장
CREATE OR REPLACE VIEW studentView
AS
SELECT sid, name, tel
 , DECODE((SELECT sid FROM grade WHERE sid=s.sid)
  , null, 0, 1) AS sub
 FROM student s;
-->뷰를 이용한 학생 전체 명단  출력 쿼리
SELECT sid, name, tel, sub
 FROM studentView
 ORDER BY sid;


--학생 검색 쿼리(성적 입력 전에 학생 정보 검색 과정에서 사용. 프로그램에서 사용 예정)
SELECT sid, name, tel, sub
 FROM studentView
 WHERE sid=1;


--성적 출력 쿼리 (프로그램에서 사용 예정)
--번호, 학생이름, 과목1, 과목2, 과목3, 총점, 평균, 판정(0 합격, 1 과락, 2 불합격)
--학생 테이블->번호, 학생이름
--성적 테이블->과목1, 과목2, 과목3
--총점, 평균, 판정 -> 계산 결과
--학생 테이블 + 성적 테이블 -> JOIN, SUB QUERY

주의) 오라클에서 NULL 데이터는 자바에서는 String 자료형인 경우에만 처리 가능.
NUMBER -> int -> 숫자 서식 지정 가능
VARCHAR2 -> String -> 문자열 서식 지정 가능
NUMBER + NULL -> String -> NULL이 아닌 경우에만 Integer.parseInt(String) 가능
VARCHAR2 + NULL -> String

--OUTER JOIN의 경우
SELECT sid, name, sub1, sub2, sub3, tot, ave 
    , ( CASE
          WHEN ave>=60 AND sub1>=40 AND sub2>=40 AND sub3>=40 THEN 0 --합격
          WHEN ave>=60 THEN 1 --과락
          ELSE 2 --불합격
      END ) AS ch
FROM (SELECT s.sid AS sid, name, sub1, sub2, sub3
    , (sub1 + sub2 + sub3) AS tot
    , ( (sub1 + sub2 + sub3) / 3 ) AS ave
  FROM student s, grade g
  WHERE s.sid = g.sid(+));


--> 뷰(View) 등록
CREATE OR REPLACE VIEW gradeView
AS
SELECT sid, name, sub1, sub2, sub3, tot, ave 
    , ( CASE
          WHEN ave>=60 AND sub1>=40 AND sub2>=40 AND sub3>=40 THEN 0 --합격
          WHEN ave>=60 THEN 1 --과락
          ELSE 2 --불합격
      END ) AS ch
FROM (SELECT s.sid AS sid, name, sub1, sub2, sub3
    , (sub1 + sub2 + sub3) AS tot
    , ( (sub1 + sub2 + sub3) / 3 ) AS ave
  FROM student s, grade g
  WHERE s.sid = g.sid(+));

--> 뷰를 이용한 성적 출력
SELECT sid, name, sub1, sub2, sub3, tot, ave, ch
 FROM gradeView
 ORDER BY sid;


--학생 삭제 쿼리
DELETE FROM student WHERE sid=1;

--성적 삭제 쿼리
DELETE FROM grade WHERE sid=1;


4. 프로그램 구성
//DBConn.java
//Student.java -> 자료형 클래스
//Grade.java -> 자료형 클래스
//StudentDAO.java -> 데이터베이스 액션
//GradeDAO.java -> 데이터베이스 액션

//Controller.java -> 서블릿 클래스. 요청 주소 분석.
//Action.java -> 액션 클래스. 액션 메소드 추가.

//StudentMain.jsp -> 학생 명단 출력 페이지. JSTL&EL 표현. 삭제 버튼 추가.
//StudentInsertForm.jsp -> 학생 입력 폼 페이지. action="서블릿주소"
//GradeMain.jsp -> 성적 출력 페이지. JSTL&EL 표현. 삭제 버튼 추가
//GradeInsertForm.jsp -> 성적 입력 폼 페이지. JSTL&EL 표현. action="서블릿주소"

//Error.jsp -> 요청 주소가 잘못되었습니다.

//web.xml -> 서블릿 주소 등록. 확장자 .it 주소 등록.

//요청주소
http://localhost:8090/프로젝트이름/StudentMain.it

5. 프로그램 소스 코드
//DBConn.java
package com.test;

import java.sql.*;

public class DBConn {

 //Connection(데이터베이스 연결) 객체 저장용 변수 선언
 private static Connection conn = null;
 
 //1. 데이터베이스 연결 과정
 public static Connection getConn()
   throws ClassNotFoundException, SQLException {

  //Connection 객체가 생성되지 않은 경우에만
  //신규 객체를 생성한다. -> SingleTone
  if (conn == null) {
   //데이터베이스 연결 액션(로그인 과정)
   Class.forName("oracle.jdbc.driver.OracleDriver");
   String url = "jdbc:oracle:thin:아이디/패스워드@211.63.89.XX:1521:xe";
   conn = DriverManager.getConnection(url);
  }
    
  return conn;
 }
 
 
 //2. 데이터베이스 연결 종료 과정
 public static void close() throws SQLException {
  if (conn != null) {
   conn.close();
  }
  conn = null; //멤버변수를 NULL 값으로 초기화
 }
 
 
}

 


//Student.java -> 자료형 클래스
package com.test;

public class Student {
 
 private int sub;
 private String sid, name, tel;

 public int getSub() {
  return sub;
 }
 public void setSub(int sub) {
  this.sub = sub;
 }
 public String getSid() {
  return sid;
 }
 public void setSid(String sid) {
  this.sid = sid;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getTel() {
  return tel;
 }
 public void setTel(String tel) {
  this.tel = tel;
 }

}

 

 


//Grade.java -> 자료형 클래스
package com.test;

public class Grade {
 
 private int ch;
 private String sid, name, sub1, sub2, sub3, tot, ave;
 
 public int getCh() {
  return ch;
 }
 public void setCh(int ch) {
  this.ch = ch;
 }
 public String getSid() {
  return sid;
 }
 public void setSid(String sid) {
  this.sid = sid;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getSub1() {
  return sub1;
 }
 public void setSub1(String sub1) {
  this.sub1 = sub1;
 }
 public String getSub2() {
  return sub2;
 }
 public void setSub2(String sub2) {
  this.sub2 = sub2;
 }
 public String getSub3() {
  return sub3;
 }
 public void setSub3(String sub3) {
  this.sub3 = sub3;
 }
 public String getTot() {
  return tot;
 }
 public void setTot(String tot) {
  this.tot = tot;
 }
 public String getAve() {
  return ave;
 }
 public void setAve(String ave) {
  this.ave = ave;
 }
 
}

 

 


//StudentDAO.java -> 데이터베이스 액션
package com.test;

import java.sql.*;
import java.util.*;

public class StudentDAO {

 public ArrayList<Student> list() {
  ArrayList<Student> result = new ArrayList<Student>();

  Connection conn = null;
  PreparedStatement pstmt = null;
  try {
   // Connection 객체 얻는 방법
   conn = DBConn.getConn();

   String sql = "SELECT sid, name, tel, sub FROM studentView ORDER BY sid";
   pstmt = conn.prepareStatement(sql);
   ResultSet rs = pstmt.executeQuery();

   while (rs.next()) {
    Student student = new Student();
    student.setSid(rs.getString("sid"));
    student.setName(rs.getString("name"));
    student.setTel(rs.getString("tel"));
    student.setSub(rs.getInt("sub"));
    result.add(student);
   }

   rs.close();

  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   try {
    if (pstmt != null) {
     pstmt.close();
    }
    // 연결 종료시 conn.close(); 사용하면 안됨.
    DBConn.close();
   } catch (Exception e) {
    e.printStackTrace();
   }
  }

  return result;
 }

 public int count() {
  int result = 0;

  Connection conn = null;
  PreparedStatement pstmt = null;
  try {
   // Connection 객체 얻는 방법
   conn = DBConn.getConn();

   String sql = "SELECT COUNT(*) AS count FROM studentView";
   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();
    }
    // 연결 종료시 conn.close(); 사용하면 안됨.
    DBConn.close();
   } catch (Exception e) {
    e.printStackTrace();
   }
  }

  return result;
 }

 public int add(Student student) {

  int result = 0;

  Connection conn = null;
  PreparedStatement pstmt = null;
  try {
   conn = DBConn.getConn();

   String sql = "INSERT INTO student (sid, name, tel) VALUES (studentSeq.nextval, ?, ?)";
   pstmt = conn.prepareStatement(sql);
   pstmt.setString(1, student.getName());
   pstmt.setString(2, student.getTel());
   pstmt.executeUpdate();

  } catch (SQLException e) {
   e.printStackTrace();
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  } finally {
   try {
    if (pstmt != null) {
     pstmt.close();
    }
    DBConn.close();
   } catch (SQLException se) {
    se.printStackTrace();
   }
  }

  return result;
 }

}

 

 


//GradeDAO.java -> 데이터베이스 액션
package com.test;

import java.sql.*;
import java.util.*;

public class GradeDAO {
 public int count() {
  int result = 0;

  Connection conn = null;
  PreparedStatement pstmt = null;
  try {
   conn = DBConn.getConn();

   String sql = "SELECT COUNT(*) AS count FROM studentView";

   pstmt = conn.prepareStatement(sql);
   ResultSet rs = pstmt.executeQuery();
   while (rs.next()) {
    result = rs.getInt("count");
   }
   rs.close();

  } catch (SQLException e) {
   e.printStackTrace();
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  } finally {
   try {
    if (pstmt != null) {
     pstmt.close();
    }
    DBConn.close();
   } catch (SQLException se) {
    se.printStackTrace();
   }
  }
  return result;
 }

 public ArrayList<Grade> list() {
  ArrayList<Grade> result = new ArrayList<Grade>();

  Connection conn = null;
  PreparedStatement pstmt = null;
  try {
   conn = DBConn.getConn();

   String sql = "SELECT sid, name, sub1, sub2, sub3, tot, ave, ch FROM gradeView ORDER BY sid";

   pstmt = conn.prepareStatement(sql);
   ResultSet rs = pstmt.executeQuery();
   while (rs.next()) {
    Grade grade = new Grade();
    grade.setSid(rs.getString("sid"));
    grade.setName(rs.getString("name"));
    grade.setSub1(rs.getString("sub1"));
    grade.setSub2(rs.getString("sub2"));
    grade.setSub3(rs.getString("sub3"));
    grade.setTot(rs.getString("tot"));
    grade.setAve(rs.getString("ave"));
    grade.setCh(rs.getInt("ch"));
    result.add(grade);

   }
   rs.close();

  } catch (SQLException e) {
   e.printStackTrace();
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  } finally {
   try {
    if (pstmt != null) {
     pstmt.close();
    }
    DBConn.close();
   } catch (SQLException se) {
    se.printStackTrace();
   }
  }

  return result;
 }

 public String searchId(String sid) {
  String result = "";

  Connection conn = null;
  PreparedStatement pstmt = null;

  try {
   conn = DBConn.getConn();
   String sql = "SELECT name FROM studentView WHERE sid =?";

   pstmt = conn.prepareStatement(sql);
   pstmt.setInt(1, Integer.parseInt(sid));
   ResultSet rs = pstmt.executeQuery();
   while (rs.next()) {
    result = rs.getString("name");
   }
   rs.close();

  } catch (SQLException e) {
   e.printStackTrace();
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  } finally {
   try {
    if (pstmt != null) {
     pstmt.close();
    }
    DBConn.close();
   } catch (SQLException se) {
    se.printStackTrace();
   }
  }

  return result;
 }

 public int add(Grade grade) {
  int result = 0;

  Connection conn = null;
  PreparedStatement pstmt = null;
  try {
   conn = DBConn.getConn();
   String sql = "INSERT INTO grade (sid, sub1, sub2, sub3) VALUES (?, ?, ?, ?)";

   pstmt = conn.prepareStatement(sql);
   pstmt.setString(1, grade.getSid());
   pstmt.setString(2, grade.getSub1());
   pstmt.setString(3, grade.getSub2());
   pstmt.setString(4, grade.getSub3());
   pstmt.executeUpdate();

  } catch (SQLException e) {
   e.printStackTrace();
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  } finally {
   try {
    if (pstmt != null) {
     pstmt.close();
    }
    DBConn.close();
   } catch (SQLException se) {
    se.printStackTrace();
   }
  }
  return result;
 }
}


------------------------------------------
팀별과제) 성적관리 서블릿 프로그램 소스 코드 작성. MVC 패턴 적용.

//Controller.java -> 서블릿 클래스. 요청 주소 분석.
//Action.java -> 액션 클래스. 액션 메소드 추가.

//StudentList.jsp -> 학생 명단 출력 페이지. JSTL&EL 표현. 삭제 버튼 추가.
//StudentInsertForm.jsp -> 학생 입력 폼 페이지. action="서블릿주소"
//GradeList.jsp -> 성적 출력 페이지. JSTL&EL 표현. 삭제 버튼 추가
//GradeInsertForm.jsp -> 성적 입력 폼 페이지. JSTL&EL 표현. action="서블릿주소"

//Error.jsp -> 요청 주소가 잘못되었습니다.

//web.xml -> 서블릿 주소 등록. 확장자 .it 주소 등록.

//요청주소
http://localhost:8090/프로젝트이름/StudentList.it


-----------------------------------------------

//Controller.java -> 서블릿 클래스. 요청 주소 분석.
package com.test;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

public class Controller extends HttpServlet {

 private static final long serialVersionUID = 1L;

 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  //사용자 정의 메소드 호출 부분 추가
  doGetPost(req, resp);
 }

 @Override
 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  //사용자 정의 메소드 호출 부분 추가
  doGetPost(req, resp);
 }
 
 //사용자 정의 메소드 (doGet, doPost 메소드에 대한 통합 액션)
 private void doGetPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  //액션 주소(*.it) 분석 및 처리 과정 추가
  String uri = request.getRequestURI();
  String result = "Error.jsp";
  
  /*
  액션클래스 action = new 액션클래스();
  if (uri.indexOf("요청주소.it") != -1) {
   result = action.요청메소드(request, response);
  }
  */
  Action action = new Action();
  if (uri.indexOf("StudentList.it") != -1) {
   result = action.studentList(request, response);
  }
  if (uri.indexOf("StudentInsertForm.it") != -1) {
   result = action.studentInsertForm(request, response);
  }
  if (uri.indexOf("StudentInsert.it") != -1) {
   result = action.studentInsert(request, response);
  }
  if (uri.indexOf("StudentDelete.it") != -1) {
   result = action.studentDelete(request, response);
  }
  if (uri.indexOf("GradeList.it") != -1) {
   result = action.gradeList(request, response);
  }
  if (uri.indexOf("GradeInsertForm.it") != -1) {
   result = action.gradeInsertForm(request, response);
  }
  if (uri.indexOf("GradeInsert.it") != -1) {
   result = action.gradeInsert(request, response);
  }
  if (uri.indexOf("GradeDelete.it") != -1) {
   result = action.gradeDelete(request, response);
  }
  
  
  if (result.indexOf("redirect:") != -1) {
   //sendRedirect 요청
   response.sendRedirect(result.substring(9));
  } else {
   //forward 요청
   RequestDispatcher dispatcher = request.getRequestDispatcher(result);
   dispatcher.forward(request, response);
  }  
  
 }
 

}

 

 


//Action.java -> 액션 클래스. 액션 메소드 추가.
package com.test;

import java.io.*;
import java.util.ArrayList;

import javax.servlet.*;
import javax.servlet.http.*;

public class Action {

 /*
 public String 메소드이름(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  return "요청주소";
 }
 */
 public String studentList(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  StudentDAO dao = new StudentDAO();
  int count = dao.count();
  ArrayList<Student> list = dao.list();  
  
  request.setAttribute("count", count);
  request.setAttribute("list", list); 
  return "StudentList.jsp";
 }


 public String studentInsertForm(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  return "StudentInsertForm.jsp";
 }

 public String studentInsert(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  request.setCharacterEncoding("UTF-8");
  String name = request.getParameter("name");
  String tel = request.getParameter("tel");

  StudentDAO dao = new StudentDAO();
  Student student = new Student();
  student.setName(name);
  student.setTel(tel);
  dao.add(student);  
  
  return "redirect:StudentList.it";
 }

 public String studentDelete(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  String sid = request.getParameter("sid");
  
  StudentDAO dao = new StudentDAO();
  dao.remove(sid);
  
  return "redirect:StudentList.it";
 }

 public String gradeList(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  GradeDAO dao = new GradeDAO();
  int count = dao.count();
  ArrayList<Grade> list = dao.list(); 
  for (Grade grade : list) {
   grade.setGrade(studentGrade(grade.getCh()));
  }
  
  request.setAttribute("count", count);
  request.setAttribute("list", list);
  
  return "GradeList.jsp";
 }

 public String gradeInsertForm(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  String sid = request.getParameter("sid");

  GradeDAO dao = new GradeDAO();
  String name = dao.searchId(sid);
  
  request.setAttribute("sid", sid);
  request.setAttribute("name", name);
  
  return "GradeInsertForm.jsp";
 }

 public String gradeInsert(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  String sid = request.getParameter("sid");
  String sub1 = request.getParameter("sub1");
  String sub2 = request.getParameter("sub2");
  String sub3 = request.getParameter("sub3");
  
  GradeDAO dao = new GradeDAO();
  Grade grade = new Grade();
  grade.setSid(sid);
  grade.setSub1(sub1);
  grade.setSub2(sub2);
  grade.setSub3(sub3);
  dao.add(grade);
  
  return "redirect:GradeList.it";
 }

 public String gradeDelete(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  String sid = request.getParameter("sid");
  
  GradeDAO dao = new GradeDAO();
  dao.remove(sid);
  
  return "redirect:GradeList.it";
 }
 
 private String studentGrade(int ch) {
  String[] array = {"합격", "과락", "불합격"};
  return array[ch];
 }

}

 

 


//StudentList.jsp -> 학생 명단 출력 페이지. JSTL&EL 표현. 삭제 버튼 추가.
<%@ 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>[성적관리]</title>

<link rel="stylesheet" type="text/css" href="MyTable.css">

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {
 $("#student").click(function() {
  $(location).attr("href", "StudentList.it");
 });
 $("#grade").click(function() {
  $(location).attr("href", "GradeList.it");
 });
 $("#studentInsertForm").click(function() {
  $(location).attr("href", "StudentInsertForm.it");
 });
 $(".deleteBtn").click(function() {
  if (confirm("선택한 자료를 삭제할까요?")) {
   $(location).attr("href", "StudentDelete.it?sid="+$(this).val());
  }
 });
});
</script>

</head>
<body>
<div>
 <div id="menu">
  <form>
   <input type="button" value="학생명단" id="student">
   <input type="button" value="성적출력" id="grade">
  </form>
 </div>
 
 <div id="content">
  <h1>[학생명단]</h1>
  <h2>전체 학생수 : ${count}명</h2>
  
  <form>
   <input type="button" value="학생추가" id="studentInsertForm">
  </form>
  
  <table id="customers">
   <tr>
    <th style="width:100px;">번호</th><th>이름</th>
    <th>전화번호</th><th style="width:200px;">성적입력여부</th>
    <th>삭제</th>
   </tr>
   <c:forEach var="student" items="${list}">
   <tr>
    <td>${student.sid}</td>
    <td>${student.name}</td>
    <td>${student.tel}</td>
    <td>${student.sub==0?"X":"O"}</td>
    <td>
    <button value="${student.sid}" class="deleteBtn"
        ${student.sub==0?"":"disabled='disabled'"}>삭제</button>
    </td>
   </tr>
   </c:forEach>
  </table>
 
 </div>
</div>
</body>
</html>

 

 

//StudentInsertForm.jsp -> 학생 입력 폼 페이지. action="서블릿주소"
<%@ 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>[성적관리]</title>
<link rel="stylesheet" type="text/css" href="MyTable.css">

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {
 $("#student").click(function() {
  $(location).attr("href", "StudentList.it");
 });
 $("#grade").click(function() {
  $(location).attr("href", "GradeList.it");
 });
 $("#name").keyup(function(){
  $("#nameLength").html($(this).val().length);
 });
 $("#tel").keyup(function(){
  $("#telLength").html($(this).val().length);
 }); 
 $("#studentInsertForm").submit(function() {
  $("#err").html("");
  if ($("#name").val()=="" || $("#tel").val()=="") {
   $("#err").html("빈 항목을 채워야 합니다.");
   return false;
  }
  return true;
 });
});
</script>

</head>
<body>
<div>
 <div id="menu">
  <form>
   <input type="button" value="학생명단" id="student">
   <input type="button" value="성적출력" id="grade">
  </form>
 </div>
 
 <div id="content">
  <h1>[학생추가]</h1>
  
  <form action="StudentInsert.it" method="post"
    id="studentInsertForm">
  <table>
   <tr>
    <td>이름*</td>
    <td>
    
    <%-- 이름 입력 폼에서 글자 수 출력 위한 <span></span> 엘리먼트 추가 --%>
    <input type="text" id="name" name="name"
      required="required"> ( <span id="nameLength">0</span> / 30 )
      
    </td>
   </tr>
   <tr>
    <td>전화*</td>
    <td>
    
    <%-- 전화 입력 폼에서 글자 수 출력 위한 <span></span> 엘리먼트 추가 --%>
    <input type="text" id="tel" name="tel"
      required="required"> ( <span id="telLength">0</span> / 30 )
      
    </td>
   </tr>
   <tr>
    <td></td>
    <td>
    
    <%-- 학생 추가 폼에 대한 서브밋 버튼 --%>
    <input type="submit" value="학생추가">
    <span id="err"></span>
    
    </td>
   </tr>
  </table>
  </form>
 </div>

</div>
</body>
</html>

 

 

 


//GradeList.jsp -> 성적 출력 페이지. JSTL&EL 표현. 삭제 버튼 추가
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%-- 성적 출력 페이지 --%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>   
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>[성적관리]</title>

<link rel="stylesheet" type="text/css" href="MyTable.css">

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {
 $("#student").click(function() {
  $(location).attr("href", "StudentList.it");
 });
 $("#grade").click(function() {
  $(location).attr("href", "GradeList.it");
 });
 $(".btnInsertForm").click(function() {
  $(location).attr("href", "GradeInsertForm.it?sid="+$(this).val());
 });
 $(".deleteBtn").click(function() {
  if (confirm("선택한 자료를 삭제할까요?")) {
   $(location).attr("href", "GradeDelete.it?sid="+$(this).val());
  }
 }); 
});
</script>

</head>
<body>
<div>
 <div id="menu">
  <form>
   <input type="button" value="학생명단" id="student">
   <input type="button" value="성적출력" id="grade">
  </form>
 </div>
 
 <div id="content">
  <h1>[성적출력]</h1>
  <h2>전체 학생수 : ${count} 명</h2>
  <table id="customers">
   <tr>
    <th>번호</th><th>이름</th>
    <th>과목1</th><th>과목2</th><th>과목3</th>
    <th>총점</th><th>평균</th><th>판정</th>
    <th></th><th></th>
   </tr>
   <c:forEach var="grade" items="${list}">
   <tr>
    <td>${grade.sid}</td>
    <td>${grade.name}</td>
    <td>${empty grade.sub1?"null":grade.sub1}</td>
    <td>${empty grade.sub2?"null":grade.sub2}</td>
    <td>${empty grade.sub3?"null":grade.sub3}</td>
    <td>${empty grade.tot?"null":grade.tot}</td>
    <td><fmt:formatNumber value="${grade.ave}" pattern="#.0" /></td>
    <td>${grade.grade}</td>
    <td>
    <button class="btnInsertForm" value="${grade.sid}"
     ${empty grade.sub1?"":"disabled='disabled'"}>성적추가</button>
    </td>
    <td>
    <button value="${grade.sid}" class="deleteBtn"
        ${empty grade.sub1?"disabled='disabled'":""}>삭제</button>
    </td>
   </tr>
   </c:forEach>
  </table>
 </div>

</div>
</body>
</html>

 

 

 


//GradeInsertForm.jsp -> 성적 입력 폼 페이지. JSTL&EL 표현. action="서블릿주소"
<%@ 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>[성적관리]</title>
<link rel="stylesheet" type="text/css" href="MyTable.css">

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {
 $("#student").click(function() {
  $(location).attr("href", "StudentList.it");
 });
 $("#grade").click(function() {
  $(location).attr("href", "GradeList.it");
 });
 $("#gradeInsertForm").submit(function () {
  $("#err").css("display", "none");
  if ($("#sub1").val() == ""
    || $("#sub1").val().match(/[^0-9]/)
    || (parseInt($("#sub1").val())>100 || parseInt($("#sub1").val())<0)) {
   $("#err").html("0~100사이의 값을 넣어주세요.");
   $("#err").css("display", "inline");
   return false;
  }
  if ($("#sub2").val() == ""
   || $("#sub2").val().match(/[^0-9]/)
   || (parseInt($("#sub2").val())>100 || parseInt($("#sub2").val())<0)) {
   $("#err").html("0~100사이의 값을 넣어주세요.");
   $("#err").css("display", "inline");
   return false;
  }
  if ($("#sub3").val() == ""
   || $("#sub3").val().match(/[^0-9]/)
   || (parseInt($("#sub3").val())>100 || parseInt($("#sub3").val())<0)) {
   $("#err").html("0~100사이의 값을 넣어주세요.");
   $("#err").css("display", "inline");
   return false;
  }
  return true;
 });
});
</script>

</head>
<body>
<div>
 <div id="menu">
  <form>
   <input type="button" value="학생명단" id="student">
   <input type="button" value="성적출력" id="grade">
  </form>
 </div>
 
 <div id="content">
 
  <h1>[성적 입력]</h1>
  <form action="GradeInsert.it" method="post"
    id="gradeInsertForm">
  <table>
   <tr>
    <td>번호*</td>
    <td><input type="text" id="sid" name="sid"
      value="${sid}" readonly="readonly" ></td>
   </tr>
   <tr>
    <td>이름*</td>
    <td><input type="text" id="name" name="name"
      value="${name}" readonly="readonly" ></td>
   </tr>
   <tr>
    <td>sub1*</td>
    <td><input type="text" id="sub1" name="sub1"
      required="required"> </td>
   </tr>
   <tr>
    <td>sub2*</td>
    <td><input type="text" id="sub2" name="sub2"
      required="required"> </td>
   </tr>
   <tr>
    <td>sub3*</td>
    <td><input type="text" id="sub3" name="sub3"
      required="required"> </td>
   </tr>
   <tr>
    <td></td>
    <td>
    <input type="submit" value="성적추가">
    <span id="err"></span>
    </td>
   </tr>
  </table>

  </form>
 
 </div>

</div>
</body>
</html>

 

 

//Error.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>성적관리</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

</head>
<body>
<div>
 <div style="margin:auto; padding-top: 100px; width:400px; text-align: center;">
  <img src="txt_error_msg404.gif"><br>
  <a href="StudentList.it">메인 화면으로 가기</a>
 </div>
</div>
</body>
</html>

 

 

//web.xml -> 서블릿 주소 등록. 확장자 .it 주소 등록.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>SampleProject</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
 
  <!-- 서블릿 주소 등록 -->
  <!-- 
  <servlet>
   <servlet-name>서블릿식별자</servlet-name>
   <servlet-class>패키지이름.컨트롤러클래스</servlet-class>
  </servlet>
  <servlet-mapping>
   <servlet-name>서블릿식별자</servlet-name>
   <url-pattern>*.확장자</url-pattern>
  </servlet-mapping>
  --> 

  <servlet>
   <servlet-name>controller</servlet-name>
   <servlet-class>com.test.Controller</servlet-class>
  </servlet>
  <servlet-mapping>
   <servlet-name>controller</servlet-name>
   <url-pattern>*.it</url-pattern>
  </servlet-mapping>
   
</web-app>

 


//요청주소
http://localhost:8090/프로젝트이름/StudentList.it

------------------------------------------------

 


 

'MVC' 카테고리의 다른 글

07일차_MVC패턴, 직원관리  (0) 2015.06.30
06일차_MVC패턴, 직원관리  (0) 2015.06.30
05일차_MVC패턴, 직원관리  (0) 2015.06.30
04일차_MVC패턴, 회원관리, 성적관리  (0) 2015.06.30
03일차(2)_모델2방식, 성적관리  (0) 2015.06.30
블로그 이미지

알 수 없는 사용자

,