Spring Framework 3-2(컨트롤러,모델,뷰)

유동현·2022년 11월 16일
0

스프링MVC

목록 보기
5/13
post-thumbnail

1. 각 DTO의 속성 정의 (DB에서 받아올값 & DB에 넣을값)

Employee

/*
 #01. 사원 데이터 자료형 클래스 (DTO)
 */

package com.test.mvc;

public class Employee
{
	
	//주요 속성 구성

/*
 이름             널?       유형           
-------------- -------- ------------ 
EMPLOYEEID     NOT NULL NUMBER       
NAME                    VARCHAR2(30) 
SSN                     CHAR(6)      
BIRTHDAY                VARCHAR2(10) 
LUNAR                   NUMBER(1)    
LUNARNAME               VARCHAR2(6)  
TELEPHONE               VARCHAR2(40) 
DEPARTMENTID            NUMBER       
DEPARTMENTNAME          VARCHAR2(30) 
POSITONID               NUMBER       
POSITIONNAME            VARCHAR2(30) 
REGIONID                NUMBER       
REGIONNAME              VARCHAR2(30) 
BASICPAY                NUMBER       
EXTRAPAY                NUMBER       
PAY                     NUMBER       
GRADE                   NUMBER(1)  
 */

private	String employeeId, name, ssn, birthday, lunarName, telephone;
	//-- 사원번호, 사원명, 주민번호, 생년월일, 양음력, 전화번호
	
private	String departmentId, departmentName;
	//-- 부서아이디, 부서명
	
private	String positionId, positionName;
	//-- 직위아이디, 직위명
	
private	String regionId, regionName;
	//-- 지역아이디, 지역명
	
private	int lunar;
	//-- 양력0, 음력1
	
private	String ssn1, ssn2;
	//-- 주민번호 앞자리, 뒷자리
	
private	int basicPay, extraPay, pay;
	//-- 기본급, 수당, 급여
	
	private int grade;
	//-- 관리자0, 일반사원 1
//세터 게터는 생략
}




Department

/*
 #02. Department.java
 - 부서 데이터 자료형 클래스(DTO)
 */
package com.test.mvc;

public class Department
{
	
	//주요 속성 구성
	private String departmentId, departmentName;
	//부서아이디, 부서명
	
	private int delCheck;
	//--삭제 가능 여부에 대한 확인
	// 참조되고 있는 경우(1 이상) 삭제 불가능.
	// 그렇지 않은 경우(0)만 삭제 가능.
//세터 게터는 생략
}




Region

/*
 #03. Region.java
 -지역 데이터 자료형 클래스(DTO)
 */

package com.test.mvc;

public class Region
{
	
	private String regionId, regionName;
	
	private int delCheck;
	//--삭제 가능 여부에 대한 확인
	// 참조되고 있는 경우(1 이상) 삭제 불가능.
	// 그렇지 않은 경우(0)만 삭제 가능.
//세터 게터는 생략
}




Position

/*
 #04.Position.java
 -직위 데이터 자료형 클래스(DTO)
 */

package com.test.mvc;

public class Position
{
	//주요 속성 구성
	private String positionId, positionName;
	//직위 아이디, 직위명
	private int minBasicPay;
	//최소 기본급
	private int delCheck;
	//--삭제 가능 여부에 대한 확인
	// 참조되고 있는 경우(1 이상) 삭제 불가능.
	// 그렇지 않은 경우(0)만 삭제 가능.
	//세터 게터는 생략
}




2. 각 DAO의 인터페이스 생성

InterFace EmployeeDAO

/*
 #05. IEmployeeDAO.java
 - 인터페이스
 */

package com.test.mvc;

import java.sql.SQLException;
import java.util.ArrayList;

public interface IEmployeeDAO
{
	//추후 EmployeeDAO 에서 정의할 것으로 예상되는 메소드에 대한 선언
	public ArrayList<Employee> list() throws SQLException;
	public ArrayList<Region> regionList() throws SQLException;
	public ArrayList<Department> departmentList() throws SQLException;
	public ArrayList<Position> positionList() throws SQLException;
	
	public int getMinBasicPay(String positionId) throws SQLException;
	public int employeeAdd(Employee employee) throws SQLException;
	public int remove(String employeeId) throws SQLException;
	public int modify(Employee employee) throws SQLException;
	public Employee searchId(String employeeId)throws SQLException; 
}




Interface DepartmentDAO

/*
 #06. IDepartmentDAO.java
 - 인터페이스
 */
public interface IDepartmentDAO
{
	public ArrayList<Department> list() throws SQLException;
	public int add(Department department) throws SQLException;
	public int remove(String departmentId) throws SQLException;
	public int modify(Department department) throws SQLException;
}




Interface RegionDAO

/*
 #07. IRegionDAO.java
 - 인터페이스
 */
public interface IRegionDAO
{	
	public ArrayList<Region> list() throws SQLException; //--출력
	public int add(Region region) throws SQLException;  //--입력
	public int remove(String regionId) throws SQLException;   //--삭제
	public int modify(Region region) throws SQLException;
}




Interface PositionDAO

/*
 #08. IPositionDAO.java
 - 인터페이스
 */
public interface IPositionDAO
{
	public ArrayList<Position> list() throws SQLException;
	public int add(Position position) throws SQLException;
	public int remove(String positionId) throws SQLException;
	public int modify(Position position) throws SQLException;
}




각 DAO 생성

EmployeeDAO

/*
 #09. EmployeeDAO.java
 - 데이터베이스 액션 처리 클래스
				   직원 데이터 입출력 및 수정 삭제 액션
				   Connection 객체에 대한 의존성 주입 준비
				   (인터페이스 속성 구성 / setter 정의)
 */

package com.test.mvc;

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

import javax.sql.DataSource;

public class EmployeeDAO implements IEmployeeDAO
{

	private DataSource dataSource;

	public void setdataSource(DataSource dataSource)
	{
		this.dataSource = dataSource;
	}

	@Override
	public ArrayList<Employee> list() throws SQLException
	{

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

		Connection conn = dataSource.getConnection();

		// sql
		String sql = "SELECT EMPLOYEEID, NAME, SSN, BIRTHDAY, LUNAR, LUNARNAME, TELEPHONE, DEPARTMENTID, DEPARTMENTNAME"
				+ ", POSITIONID, POSITIONNAME, REGIONID, REGIONNAME, BASICPAY, EXTRAPAY, PAY, GRADE FROM EMPLOYEEVIEW";

		// 작업객체
		PreparedStatement pstmt = conn.prepareStatement(sql);

		ResultSet rs = pstmt.executeQuery();

		while (rs.next())
		{

			Employee employee = new Employee();

			employee.setEmployeeId(rs.getString("EMPLOYEEID"));
			employee.setName(rs.getString("NAME"));
			employee.setSsn(rs.getString("SSN"));
			employee.setBirthday(rs.getString("BIRTHDAY"));
			employee.setLunar(rs.getInt("LUNAR"));
			employee.setLunarName(rs.getString("LUNARNAME"));
			employee.setTelephone(rs.getString("TELEPHONE"));
			employee.setDepartmentId(rs.getString("DEPARTMENTID"));
			employee.setDepartmentName(rs.getString("DEPARTMENTNAME"));
			employee.setPositionId(rs.getString("POSITIONID"));
			employee.setPositionName(rs.getString("POSITIONNAME"));
			employee.setRegionId(rs.getString("REGIONID"));
			employee.setRegionName(rs.getString("REGIONNAME"));
			employee.setBasicPay(rs.getInt("BASICPAY"));
			employee.setExtraPay(rs.getInt("EXTRAPAY"));
			employee.setPay(rs.getInt("PAY"));
			employee.setGrade(rs.getInt("GRADE"));

			result.add(employee);

		}

		rs.close();
		pstmt.close();
		conn.close();

		return result;
	}

	@Override
	public ArrayList<Region> regionList() throws SQLException
	{
		ArrayList<Region> result = new ArrayList<Region>();
		
		Connection conn = dataSource.getConnection();
		
		//sql
		String sql = "SELECT REGIONID, REGIONNAME, DELCHECK FROM REGIONVIEW ORDER BY REGIONID";
		
		PreparedStatement pstmt = conn.prepareStatement(sql);
		
		ResultSet rs = pstmt.executeQuery();
		
		while (rs.next())
		{
			Region region = new Region();
			
			region.setRegionId(rs.getString("REGIONID"));
			region.setRegionName(rs.getString("REGIONNAME"));
			region.setDelCheck(rs.getInt("DELCHECK"));
			
			result.add(region);
		}
		
		rs.close();
		pstmt.close();
		conn.close();
		
		return result;
	}

	@Override
	public ArrayList<Department> departmentList() throws SQLException
	{
		ArrayList<Department> result = new ArrayList<Department>();
		
		Connection conn = dataSource.getConnection();
		
		//sql
		String sql = "SELECT DEPARTMENTID, DEPARTMENTNAME, DELCHECK FROM DEPARTMENTVIEW ORDER BY DEPARTMENTID";
		
		PreparedStatement pstmt = conn.prepareStatement(sql);
		
		ResultSet rs = pstmt.executeQuery();
		
		while (rs.next())
		{
			Department department = new Department();
			
			department.setDepartmentId(rs.getString("DEPARTMENTID"));
			department.setDepartmentName(rs.getString("DEPARTMENTNAME"));
			department.setDelCheck(rs.getInt("DELCHECK"));
			
			result.add(department);
		}
		
		rs.close();
		pstmt.close();
		conn.close();
		
		return result;
	}

	@Override
	public ArrayList<Position> positionList() throws SQLException
	{
		ArrayList<Position> result = new ArrayList<Position>();
		
		Connection conn = dataSource.getConnection();
		
		//sql
		String sql = "SELECT POSITIONID, POSITIONNAME, MINBASICPAY, DELCHECK FROM POSITIONVIEW ORDER BY POSITIONID";
		
		PreparedStatement pstmt = conn.prepareStatement(sql);
		
		ResultSet rs = pstmt.executeQuery();
		
		while (rs.next())
		{
			Position position = new Position();
			
			position.setPositionId(rs.getString("POSITIONID"));
			position.setPositionName(rs.getString("POSITIONNAME"));
			position.setMinBasicPay(rs.getInt("MINBASICPAY"));
			position.setDelCheck(rs.getInt("DELCHECK"));
			
			result.add(position);
		}
		
		rs.close();
		pstmt.close();
		conn.close();
		
		
		return result;
	}

	@Override
	public int getMinBasicPay(String positionId) throws SQLException
	{
		
		int result = 0;
		
		Connection conn = dataSource.getConnection();
		
		String sql = "SELECT MINBASICPAY FROM POSITIONVIEW WHERE POSITIONID = ?";
		
		PreparedStatement pstmt = conn.prepareStatement(sql);
		
		pstmt.setInt(1, Integer.parseInt( positionId));
		
		result = pstmt.executeUpdate(); 
		
		pstmt.close();
		conn.close();
		
		return result;
	}

	@Override
	public int employeeAdd(Employee employee) throws SQLException
	{
		int result = 0;
		
		Connection conn = dataSource.getConnection();
		
		String sql = "INSERT INTO EMPLOYEE(EMPLOYEEID, NAME, SSN1, SSN2, BIRTHDAY, LUNAR, TELEPHONE, DEPARTMENTID"
				+ ", POSITIONID, REGIONID, BASICPAY, EXTRAPAY) VALUES(EMPLOYEESEQ.NEXTVAL"
				+ ", ?, ? , CRYPTPACK.ENCRYPT(?, ?)"
				+ ", TO_DATE(?,'YYYY-MM-DD'), ?, ?, ?,?,?, ?, ?)";
		
		PreparedStatement pstmt = conn.prepareStatement(sql);
		
		pstmt.setString(1, employee.getName());
		pstmt.setString(2, employee.getSsn1());
		pstmt.setString(3, employee.getSsn2());
		pstmt.setString(4, employee.getSsn2());
		pstmt.setString(5, employee.getBirthday());
		pstmt.setInt(6, employee.getLunar());
		pstmt.setString(7, employee.getTelephone());
		pstmt.setInt(8, Integer.parseInt(employee.getDepartmentId()));
		pstmt.setInt(9, Integer.parseInt(employee.getPositionId()));
		pstmt.setInt(10, Integer.parseInt(employee.getRegionId()));
		pstmt.setInt(11, employee.getBasicPay());
		pstmt.setInt(12, employee.getExtraPay());
		
		
		
		return result;
	}

	@Override
	public int remove(String employeeId) throws SQLException
	{
		
		int result = 0;
		Connection conn = dataSource.getConnection();
		String sql = "DELETE FROM EMPLOYEE WHERE EMPLOYEEID=?";
		PreparedStatement pstmt = conn.prepareStatement(sql);
		pstmt.setInt(1, Integer.parseInt(employeeId));
		result = pstmt.executeUpdate();
		pstmt.close();
		
		conn.close();
		
		return result;
	}
	
	
	

	@Override
	public int modify(Employee employee) throws SQLException
	{
		int result = 0;
		Connection conn = dataSource.getConnection();
		String sql = "UPDATE EMPLOYEE"
				  + " SET NAME=?, BIRTHDAY=TO_DATE(?, 'YYYY-MM-DD')"
				     + ", LUNAR=?, TELEPHONE=?"
				     + ", DEPARTMENTID=?, POSITIONID=?, REGIONID=?"
				     + ", BASICPAY=?, EXTRAPAY=?"
				     + ", SSN1=?, SSN2=CRYPTPACK.ENCRYPT(?, ?)"
				  + " WHERE EMPLOYEEID=?";
		PreparedStatement pstmt = conn.prepareStatement(sql);
		pstmt.setString(1, employee.getName());
		pstmt.setString(2, employee.getBirthday());
		pstmt.setInt(3, employee.getLunar());
		pstmt.setString(4, employee.getTelephone());
		pstmt.setInt(5, Integer.parseInt(employee.getDepartmentId()));
		pstmt.setInt(6, Integer.parseInt(employee.getPositionId()));
		pstmt.setInt(7, Integer.parseInt(employee.getRegionId()));
		pstmt.setInt(8, employee.getBasicPay());
		pstmt.setInt(9, employee.getExtraPay());
		pstmt.setString(10, employee.getSsn1());
		pstmt.setString(11, employee.getSsn2());
		pstmt.setString(12, employee.getSsn2());
		pstmt.setInt(13, Integer.parseInt(employee.getEmployeeId()));
		result = pstmt.executeUpdate();
		
		pstmt.close();
		conn.close();
		
		return result;
	}

	@Override
	public Employee searchId(String employeeId) throws SQLException
	{
Employee result = new Employee();
		
		Connection conn = dataSource.getConnection();
		String sql = "SELECT EMPLOYEEID, NAME, SSN1"
				 + ", TO_CHAR(BIRTHDAY, 'YYYY-MM-DD') AS BIRTHDAY, LUNAR"
				 + ", TELEPHONE, DEPARTMENTID, POSITIONID, REGIONID"
				 + ", BASICPAY, EXTRAPAY"
				 + " FROM EMPLOYEE"
				 + " WHERE EMPLOYEEID=?";
		PreparedStatement pstmt = conn.prepareStatement(sql);
		pstmt.setInt(1, Integer.parseInt(employeeId));
		ResultSet rs = pstmt.executeQuery();
		while (rs.next())
		{	
			// 여기는 employee 객체 생성하면 안 된다.
			
			result.setEmployeeId(rs.getString("EMPLOYEEID"));
			result.setName(rs.getString("NAME"));
			result.setSsn1(rs.getString("SSN1"));
			result.setBirthday(rs.getString("BIRTHDAY"));
			result.setLunar(rs.getInt("LUNAR"));
			result.setTelephone(rs.getString("TELEPHONE"));
			result.setDepartmentId(rs.getString("DEPARTMENTID"));
			result.setPositionId(rs.getString("POSITIONID"));
			result.setRegionId(rs.getString("REGIONID"));
			result.setBasicPay(rs.getInt("BASICPAY"));
			result.setExtraPay(rs.getInt("EXTRAPAY"));
		}
		rs.close();
		pstmt.close();
		conn.close();
		
		return result;
	}

}




DepartmentDAO

/*
 #10. DepartmetDAO.java
 - 데이터베이스 액션 처리 클래스
				   직원 데이터 입출력 및 수정 삭제 액션
				   Connection 객체에 대한 의존성 주입 준비
				   (인터페이스 속성 구성 / setter 정의)
 */
package com.test.mvc;

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

import javax.sql.DataSource;

public class DepartmentDAO implements IDepartmentDAO
{
	
	private DataSource dataSource;
	

	public void setDatasource(DataSource dataSource)
	{
		this.dataSource = dataSource;
	}

	@Override
	public ArrayList<Department> list() throws SQLException
	{
		
		ArrayList<Department> result = new ArrayList<Department>();
		
		Connection conn = dataSource.getConnection();
		
		String sql = "SELECT DEPARTMENTID, DEPARTMENTNAME, DELCHECK FROM DEPARTMENTVIEW ORDER BY DEPARTMENTID";
		
		PreparedStatement pstmt = conn.prepareStatement(sql);
		
		ResultSet rs = pstmt.executeQuery();
		
		while (rs.next())
		{
			Department department = new Department();
			
			department.setDepartmentId(rs.getString("DEPARTMENTID"));
			department.setDepartmentName(rs.getString("DEPARTMENTNAME"));
			department.setDelCheck(rs.getInt("DELCHECK"));
			result.add(department);
		}
		
		rs.close();
		pstmt.close();
		conn.close();
		
		return result;
	}

	@Override
	public int add(Department department) throws SQLException
	{
		int result = 0;
		
		Connection conn = dataSource.getConnection();
		
		String sql = "INSERT INTO DEPARTMENT(DEPARTMENTID, DEPARTMENTNAME) VALUES(DEPARTMENTSEQ.NEXTVAL, ?)";
		
		PreparedStatement pstmt = conn.prepareStatement(sql);
		
		pstmt.setString(1, department.getDepartmentName());
		
		result = pstmt.executeUpdate();
		
		pstmt.close();
		
		conn.close();
		
		return result;
	}

	@Override
	public int remove(String departmentId) throws SQLException
	{
		int result = 0;
		
		Connection conn = dataSource.getConnection();
		
		String sql = "DELETE FROM DEPARTMENT WHERE DEPARTMENTID = ?";
		
		PreparedStatement pstmt = conn.prepareStatement(sql);
		
		pstmt.setInt(1, Integer.parseInt(departmentId));
		
		result = pstmt.executeUpdate();
		
		pstmt.close();
		
		conn.close();
		
		
		return result;
	}

	@Override
	public int modify(Department department) throws SQLException
	{
		int result = 0;
		
		Connection conn = dataSource.getConnection();
		
		String sql = "UPDATE DEPARTMENT SET DEPARTMENTNAME = ? WHERE DEPARTMENTID = ?";
		
		PreparedStatement pstmt = conn.prepareStatement(sql);
		
		pstmt.setString(1, department.getDepartmentName());
		pstmt.setInt(2, Integer.parseInt(department.getDepartmentId()));
		
		result = pstmt.executeUpdate();
		
		pstmt.close();
		conn.close();
		return result;
	}

	
	
}




RegionDAO

*DepartmentDAO 와 동일하게 list,add,remove,modify - #11

PositionDAO

*DepartmentDAO 와 동일하게 list,add,remove,modify - #12번



view 구성

EmployeeMenu.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<% 
   request.setCharacterEncoding("UTF-8");
   String cp = request.getContextPath();
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>EmployeeMenu.jsp</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="<%=cp %>/css/mainStyle.css">
<style type="text/css">

	.btn-group{width: 100%;}
	.menubtn {width: 20%; font-weight: bold;}
</style>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
</head>
<body>

<!--------------------------------------------------
    #13. EmployeeMenu.jsp
   -메인 메뉴 페이지 구성
    -로그아웃 기능(버튼) 추가 구성
---------------------------------------------------->

<div class="btn-group" role="group">
   <a href="" role="button" class="menubtn btn btn-success btn-lg">직원 관리</a>
   <a href="" role="button" class="menubtn btn btn-success btn-lg">지역 관리</a>
   <a href="" role="button" class="menubtn btn btn-success btn-lg">부서 관리</a>
   <a href="" role="button" class="menubtn btn btn-success btn-lg">직위 관리</a>
   
   <a href="" class="menu  btn btn-success btn-lg">로그 아웃</a>
   
</div>


</body>
</html>




EmployeeList.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> <!-- 이렇게 구성하면 JSTL c: 처럼 core의 포맷을 사용할  수 있다.  -->
<% 
	request.setCharacterEncoding("UTF-8");
	String cp = request.getContextPath();
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="<%=cp %>/css/mainStyle.css">

<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

</head>
<body>

<!--------------------------------------------------
    #14. EmployeeList.jsp
   -직원 리스트 출력 페이지
    -관리자가 접근하는 직원 리스트 출력 페이지
    (일반 직원이 접근하는 직원 리스트 출력 페이지는 EmpList.jsp 로 구성할 예정)
---------------------------------------------------->

<div>
	<!--메뉴 영역  -->
	<div>
		<c:import url="EmployeeMenu.jsp"></c:import>
	</div>
	
	<!--콘텐츠 영역  --><div id="content">
	
		<h1>[직원 관리] > [직원 리스트]</h1>
		<hr>
	<div>
		<form action="">
			<input type="button" value="직원 추가" class="btn">
		</form>
	</div>
	<br><br>
	
	
	  <!--------------------------------------------------------
       EMPLOYEEID    NAME SSN BIRTHDAY LUNAR  LUNARNAME   TELEPHONE 
       DEPARTMENTID  POSITIONID REGIONID      
      BASICPAY  EXTRAPAY   PAY   GRADE  
       
       ---------------------------------------------------------->
      <table id="customers" class="table">
         <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>
            <th>삭제</th>
         </tr>
          
         <tr>
            <td>1</td>
            <td>조현하</td>
            <td>981212</td>
            <td>1998-12-12</td>
            <td>양력</td>
            <td>010-1234-1234</td>
            <td>서울</td>
            <td>개발부</td>
            <td>사원</td>
            <td>1500000</td>
            <td>1500000</td>
            <td>3000000</td>
            <td>관리자</td>
            
            <td><button type="button" class="btn">수정</button></td>
            <td><button type="button" class="btn">삭제</button></td>
         </tr>
         
         <tr>
            <td>2</td>
            <td>정영준</td>
            <td>991111</td>
            <td>1999-11-11</td>
            <td>양력</td>
            <td>010-2345-2345</td>
            <td>경기</td>
            <td>인사부</td>
            <td>대리</td>
            <td>2500000</td>
            <td>500000</td>
            <td>3000000</td>
            <td>일반사원</td>
            
            <td><button type="button" class="btn">수정</button></td>
            <td><button type="button" class="btn">삭제</button></td>
         </tr> 
         
      
      </table>  
	
	
	
	</div>
	
	
	<!-- 회사 소개 및 어플리케이션 소개  -->
	
	
</div>


</body>
</html>




Controller 구성

EmployeeListController

/*=================================
	#15 EmployeeListController.java
	- 사용자 정의 컨트롤러 클래스
	- 리스트 페이지 요청에 대한 액션 처리
	- DAO 객체에 대한 의존성 주입(DI)을 위한 준비.
	 → 인터페이스 자료형
	 → setter 메소드 정의
	
==================================*/

package com.test.mvc;

import java.util.ArrayList;

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

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;


//※ Spring 이 제공하는 『Controller』 인터페이스를 구현함으로써
// 사용자 정의 컨트롤러 클래스를 구성한다.


public class EmployeeListController implements Controller
{
	//인터페이스 형태의 자료형 멤버 구성
	
	
	private IEmployeeDAO dao;
	
	
	
	public void setDao(IEmployeeDAO dao)
	{
		this.dao = dao;
	}
	
	//Controller 인페이스의 handleRequest()메소드 재정의

	@Override
	public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		
		//하는 일은 doGet , doPost 와 같다.
		
		//컨트롤러 내부 액션 처리 코드
		
		
		
		ModelAndView mav = new ModelAndView();
		
		
		ArrayList<Employee> employeeList = new ArrayList<Employee>();
		
		
		try
		{
			
			employeeList = dao.list();
			
			mav.addObject("employeeList", employeeList);
			
			mav.setViewName("/WEB-INF/view/EmployeeList.jsp");
			
		} catch (Exception e)
		{
			System.out.println(e.toString());
			// TODO: handle exception
		}
		
		
		return mav;
	}	
}




.xml 수정

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	version="3.1">
	<display-name>mvcApp01</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>
	
	<!-- ※ Spring MVC Framework 등록 -->
	<!--  → Front Controller 등록 -->
	<!--     →등록 대상은 DispatcherServlet 객체 등록 -->
		
	<!-- #16 ※ 스프링 환경 설정 -->
	<!-- -ContextLoaderListener 
		 : 서로 다른 DispatcherServlet 이 공통으로 사용된 빈 설정 -->
	<!-- 『<context-param>』 태그로 설정 파일을 지정하지 않으면 -->
	<!-- 『applicationContext.xml』이 설정 파일이 된다. -->
	
	<!-- dispatcher-servlet이 공통적으로 사용하게 될 빈의 위치를 알려주는것  -->
	<!-- <context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
			/WEB-INF/service.xml,
			/WEB-INF/common.xml
		</param-value>
	</context-param>
	
	 -->
	
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	
	<!-- 스프링 프론트 컨트롤러 -->
	<servlet>
	<servlet-name>dispatcher</servlet-name>
	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	
	<!-- <init-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
			/WEB-INF/dispatcher-servlet.xml,
			/WEB-INF/front.xml
		</param-value>
	</init-param>
	 -->
	 
	 <load-on-startup>1</load-on-startup>
	</servlet>
	
	
	<!-- ※ 『<load-on-startup>』  -->
	<!--     - 『web.xml』에서 servlet을 설정할 때 사용되며, 설정되는 값은 숫자이다.
			 - 서블릿은 최초 요청이 들어올 때 초기화된다.
			   클래스 로딩 및 인스턴스 초기화 설정을 해야 하는 것이다.
			   이렇게 되면 서버가 올라가고 맨 처음 호출한 유저는
			   일반적으로 처리되는 시간보다 오래 걸리게 된다.
			   이와 같은 상황을 방지하기 위해
			   『<load-on-startup>』 엘리먼트를 사용한다.
			 - 여기에 설정되는 숫자는 0보다 크면
			   서버가 구동되면서 서블릿을 초기화한다.
			   또한, 이 숫자는 서블릿 인스턴스 생성 갯수가 아니라
			   우선순위이다.
			   즉, 0보다 큰 값 중에서 가장 낮은 수가 가장 먼저 초기화되는 것이다.
			   같은 값이 존재할 경우 먼저 작성된 서블릿부터 초기화 된다.
	
	 -->
	
	
	
	
	<servlet-mapping>
	<servlet-name>dispatcher</servlet-name>
	<url-pattern>*.action</url-pattern>
	</servlet-mapping>
	
	<!-- ※ 인코딩 필터 등록 -->
	<!-- → CharacterEncodingFilter -->
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		
		<!-- 필터 파라미터 초기값 지정 -->
		<init-param>
			<param-name>encoding</param-name> <!--CharacterEncodingFilter 에서 쓰는 파라미터  -->
			<param-value>UTF-8</param-value>
		</init-param>
		
	</filter>
	
	
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern> <!-- 서블릿 컨텍스트의 범위안에 있는 모든 요청에 대해 UTF-8 encoding 필터를 적용하겠다. -->
			<!-- 즉 모든 요청에 대해 request.setCharacterEncoding("UTF-8")이 수행되는 것과 같은 역할을 하고 있다고 볼 수 있겠다. -->
	</filter-mapping>
	
</web-app>

ContextLoaderListener 추가설명
링크텍스트
링크텍스트
링크텍스트
링크텍스트
링크텍스트
링크텍스트




Dispatcher-servlet 구성

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
	<context:component-scan
		base-package="org.springframework.samples.petclinic.web" />

	<!-- ※ 『dispatcher-servlet.xml』 의 기본 샘플코드 -->
	<!--  이코드는 기본설정에 대한 템블릿을 복사하기 위해 스프링 doc를 참조하여 작성한다. -->
	<!--  ① 『C:\Downloads\s-f-3.0.2-with-docs\spring-framework-3.0.2.RELEASE\docs\spring-framework-reference\htmlsingle』경로로 이동-->
	<!--  ②『spring-framework-reference.html』파일 실행-->
	<!--  ③pdf의 경우 본문페이지 425페이지 찾아서 이동 450/ 805 페이지로 이동-->
	<!--  ④ 페이지 하단의 XML 파일 샘플코드 복사 & 붙여넣기 -->
	
	
	
	<!-- ※ 사용자 정의 Controller 객체 등록 및 요청 URL 매핑 주소 등록 -->
	<!-- URL 매핑하려면 bean의 name 속성 -->
	
	
	<!-- DataSource →SimpleDriverDataSource -->
	<bean id="myDataSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
		<property name="driverClass" value="oracle.jdbc.driver.OracleDriver"></property>
		<property name="url" value="jdbc:oracle:thin:@~~~~~~:1521:xe"></property>
		<property name="username" value="scott"></property>
		<property name="password" value="tiger"></property>
	</bean>
	
	<!-- DAO 등록 -->
	
	<bean id="employeeDAO" class="com.test.mvc.EmployeeDAO">
		<property name="dataSource" ref="myDataSource"></property>
	</bean>
	
	
	<!-- 직원 리스트 Controller 등록 -->	
	<bean name="/employeelist.action" class="com.test.mvc.EmployeeListController">
	
	<property name="dao" ref="employeeDAO"></property>
	
	</bean>
	
	
</beans>

applicationContext.xml

  • ContextLoaderListener 에서 bean지정을 안해주었기에 applicationContext.xml이 기본경로로 등록되어 만들어주는 .xml

  • 위치는 C:\Downloads\s-f-3.0.2-with-docs\spring-framework-3.0.2.RELEASE\docs\spring-framework-reference\htmlsingle\spring-framework-reference.html
    →VII. Appendices > C. XML Schema-based configuration > C.2.2. The util schema

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">




</beans>

EmployeeList.jsp 수정

  • 이제 EmployeeController에서 의존객체 dao를 받을수 있고 각 dao에서도 의존객체 dataSource를 받을수있게 Dispatcher-servlet(Front-Controller)에서 지정해주었기때문에
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> <!-- 이렇게 구성하면 JSTL c: 처럼 core의 포맷을 사용할  수 있다.  -->
<% 
	request.setCharacterEncoding("UTF-8");
	String cp = request.getContextPath();
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="<%=cp %>/css/mainStyle.css">

<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

</head>
<body>

<!--------------------------------------------------
    #14. EmployeeList.jsp
   -직원 리스트 출력 페이지
    -관리자가 접근하는 직원 리스트 출력 페이지
    (일반 직원이 접근하는 직원 리스트 출력 페이지는 EmpList.jsp 로 구성할 예정)
---------------------------------------------------->

<div>
	<!--메뉴 영역  -->
	<div>
		<c:import url="EmployeeMenu.jsp"></c:import>
	</div>
	
	<!--콘텐츠 영역  --><div id="content">
	
		<h1>[직원 관리] > [직원 리스트]</h1>
		<hr>
	<div>
		<form action="">
			<input type="button" value="직원 추가" class="btn">
		</form>
	</div>
	<br><br>
	
	
	  <!--------------------------------------------------------
       EMPLOYEEID    NAME SSN BIRTHDAY LUNAR  LUNARNAME   TELEPHONE 
       DEPARTMENTID  POSITIONID REGIONID      
      BASICPAY  EXTRAPAY   PAY   GRADE  
       
       ---------------------------------------------------------->
      <table id="customers" class="table">
         <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>
            <th>삭제</th>
         </tr>
      
         <c:forEach var = "employee" items="${employeeList}">
         <tr>
             <td>${employee.employeeId }</td>
             <td>${employee.name }</td>
             <td>${employee.ssn }-*******</td>
             <td>${employee.birthday }</td>
             <td>${employee.lunarName }</td>
             <td>${employee.telephone }</td>
             <td>${employee.regionName }</td>
             <td>${employee.departmentName }</td>
             <td>${employee.positionName }</td>
             
             <%-- <td>${employee.basicPay }</td> --%>
             <td>
             	<fmt:formatNumber value="${employee.basicPay }" groupingUsed="true"></fmt:formatNumber>
             </td>
             <!--  기본급을 1,500,000 이렇게 만듬  groupingUsed="true" 는 디폴드라 생략해도 된다.-->
             
             <%-- <td>${employee.extraPay }</td> --%>
             <td>
             	<fmt:formatNumber value="${employee.extraPay}" groupingUsed="true"></fmt:formatNumber>
             </td>
             
             <%-- <td>${employee.pay }</td> --%>
             <td>
             	<fmt:formatNumber value="${employee.pay}" groupingUsed="true"></fmt:formatNumber>
             </td>
             
             
             <%-- <td>${employee.grade }</td> --%>
             <td>${employee.grade==0? "일반사원" : "관리자" }</td> <%-- 삼항 연산자 활용 --%>
         
         	<td>
         		<button type="button" class="btn updateBtn">수정</button>
         	</td>
         
         	<td>
         		<button type="button" class="btn deleteBtn">삭제</button>
         	</td>
         
         </tr>
         
         </c:forEach>
                
      </table>  

	</div>	
	<!-- 회사 소개 및 어플리케이션 소개  -->	
</div>


</body>
</html>

오늘의 실습 결과

0개의 댓글