[MVC] 데이터 검색

heubanufi·2024년 4월 9일

JSP/Servlet

목록 보기
4/4


index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>작업선택</title>
<script>
	function all_search(frm){
		//frm.action = "list.jsp"; //예전방식 JSP 직접 호출
		frm.action = "list"; //list 요청
		frm.submit();
	}
	function dept_search(frm){
		//frm.action = "dept.jsp";
		frm.action = "dept";
		frm.submit();
	}
	function fullname_search(frm){
		frm.action = "fullname";
		frm.submit();
	}
</script>
</head>
<body>
	<h1>작업선택</h1>
	
	<h2>form method="post" 요청</h2>
	<form method="post">
		<input type="button" value="전체보기" onclick="all_search(this.form)">
		<input type="button" value="부서코드검색" onclick="dept_search(this.form)">
		<input type="button" value="성명검색(성,이름포함)" onclick="fullname_search(this.form)">
	</form>
	<hr>
	
	<h2>a태그 사용 get 방식 요청</h2>
	<a href="list">전체보기</a>
	<a href="dept">부서코드검색</a>
	<a href="fullname">성명검색</a>
</body>
</html>

전체보기

list.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>
</head>
<body>
	<h1>전체목록[list.jsp]</h1>
	<h2>사번, 성명, 직종코드, 급여, 부서코드</h2>
	<ul>
	<c:forEach var="vo" items="${list }">
		<li>
			${vo.employeeId }, 
			${vo.firstName } ${vo.lastName }, 
			${vo.jobId },
			${vo.salary },
			${vo.departmentId }
		</li>
	</c:forEach>
	</ul>
</body>
</html>

mapper.xml

<mapper namespace="hr">

	<!-- 전체 직원 목록 조회 -->
	<select id="list" resultType="com.mystudy.model.vo.EmployeeVO">
		SELECT * 
		FROM EMPLOYEES
		ORDER BY EMPLOYEE_ID
	</select>

</mapper>

EmployeeDAO.java

	//전체 직원 목록 조회
	public static List<EmployeeVO> getList(){
		try(SqlSession ss = DBService.getFactory().openSession()){
			return ss.selectList("hr.list");
		}catch(Exception e) {
			e.printStackTrace();
		}
		return null;
	}

ListController.java

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


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		System.out.println("> doGet() 시작");
		System.out.println(">> doGet() 업무처리");
		//db에서 데이터 가져와서 list.jsp 페이지에서 사용할 수 있도록 전달
		//1. DB연결하고 데이터 가져오기
		List<EmployeeVO> list = EmployeeDAO.getList();
		
		//2. 응답페이지(list.jsp)에 전달
		request.setAttribute("list", list);
		
		//3. 페이지 전환 - 응답할 페이지(list.jsp)로 전환(포워딩)
		request.getRequestDispatcher("list.jsp").forward(request, response);
		
		System.out.println("> doGet() 종료");
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("> doPost() 시작");
		//한글처리
		request.setCharacterEncoding("UTF-8");
		
		doGet(request, response);
		System.out.println("> doPost() 종료");
	}
	
	private void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("---> process() 시작");
		//1. DB연결하고 데이터 가져오기
		List<EmployeeVO> list = EmployeeDAO.getList();
		
		//2. 응답페이지(list.jsp)에 전달
		request.setAttribute("list", list);
		
		//3. 페이지 전환 - 응답할 페이지(list.jsp)로 전환(포워딩)
		request.getRequestDispatcher("list.jsp").forward(request, response);
		System.out.println("---> process() 끝");
	}

}

부서번호검색

dept.jsp

	<h1>부서코드검색[dept.jsp]</h1>
	<form action="deptList" method="post">
		부서코드: <input type="text" name="deptno">
		<input type="submit" value="부서코드로 검색">
	</form>

deptList.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
	<h1>부서코드검색결과[deptList.jsp]</h1>
	<h2>사번, 성명, 직종코드, 급여, 부서코드</h2>
	<ul>
	<c:forEach var="vo" items="${list }">
		<li>
			${vo.employeeId }, 
			${vo.firstName } ${vo.lastName }, 
			${vo.jobId },
			${vo.salary },
			${vo.departmentId }
		</li>
	</c:forEach>
	</ul>

mapper.xml

	<!-- 부서 직원 목록 조회 -->
	<select id="deptList" parameterType="_int" resultType="employeeVO">
		SELECT * 
		FROM EMPLOYEES
		WHERE DEPARTMENT_ID = #{departmentId}
		ORDER BY EMPLOYEE_ID
	</select>

EmployeeDAO.java

	//부서코드로 검색
	public static List<EmployeeVO> getDeptList(int deptno){
		try(SqlSession ss = DBService.getFactory().openSession()){
			return ss.selectList("hr.deptList", deptno);
		}catch(Exception e) {
			e.printStackTrace();
		}
		return null;
	}

deptController.java

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

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// dept.jsp 페이지로 응답처리(페이지 전환/이동)
		System.out.println(":: DeptController.doGet() 실행");
		request.getRequestDispatcher("dept.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println(":: DeptController.doPost() 실행");
		request.setCharacterEncoding("UTF-8");
		doGet(request, response);
	}

}

deptListController.java

@WebServlet("/deptList")
public class DeptListController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		// 전달받은 부서코드로 DB데이터 조회 후 deptList.jsp 응답처리(위임)
		//1. 전달받은 파라미터 값 확인 추출(부서코드: deptno)
		int deptno = Integer.parseInt(request.getParameter("deptno"));
		System.out.println("> deptno: " + deptno);
		
		//2. DB에서 해당부서(deptno)에 있는 직원 조회(DAO 사용)
		List<EmployeeVO> list = EmployeeDAO.getDeptList(deptno);
		
		//3. 조회된 데이터를 응답페이지 (deptList.jsp)에서 사용하도록 저장한다
		request.setAttribute("list", list);
		
		//4. 응답페이지(deptList.jsp)로 응답 위임(전가)처리
		request.getRequestDispatcher("deptList.jsp").forward(request, response);
	}
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

}

성명검색

fullname.jsp

	<h1>성명검색(성,이름포함) [fullname.jsp]</h1>
		<form action="fullnameList" method="post">
		성명: <input type="text" name="name">
		<input type="submit" value="성명으로 검색">
	</form>

fullnameList.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>   

<title>이름으로검색</title>
</head>
<body>
	<h1>이름으로검색[fullnameList.jsp]</h1>
	<h2>사번, 성명, 직종코드, 급여, 부서코드</h2>
	<ul>
	<c:forEach var="vo" items="${list }">
		<li>
			${vo.employeeId }, 
			${vo.firstName } ${vo.lastName }, 
			${vo.jobId },
			${vo.salary },
			${vo.departmentId }
		</li>
	</c:forEach>
	</ul>
</body>

mapper.xml

	<!--성명 검색 (성,이름에서 찾기)-->
	<select id="fullnameList" resultType="employeeVO">
		SELECT *
		FROM EMPLOYEES
		WHERE UPPER(FIRST_NAME) = UPPER(#{name})
		    OR UPPER(LAST_NAME) = UPPER(#{name}) 
		ORDER BY EMPLOYEE_ID
	</select>

EmployeeDAO.java

	//성명검색(성, 이름 모두에서 찾기)-getFullnameList
	public static List<EmployeeVO> getFullnameList(String name){
		try(SqlSession ss = DBService.getFactory().openSession()){
			return ss.selectList("hr.fullnameList", name);
		}catch(Exception e) {
			e.printStackTrace();
		}
		return null;
	}

fullnameController.java

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

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println(":: fullnameController.doGet() 실행");
		request.getRequestDispatcher("fullname.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println(":: fullnameController.doPost() 실행");
		//한글처리
		request.setCharacterEncoding("UTF-8");
		doGet(request, response);
	}

}

fullnameListController.java

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

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//한글처리
		request.setCharacterEncoding("UTF-8");
		//1. 전달받은 파라미터 값 확인 추출(이름: name)
				String name = request.getParameter("name");
				System.out.println("> name: " + name);
				
				//2. DB에서 이름 조회(DAO 사용)
				List<EmployeeVO> list = EmployeeDAO.getFullnameList(name);
				
				//3. 조회된 데이터를 응답페이지 (fullnameList.jsp)에서 사용하도록 저장한다
				request.setAttribute("list", list);
				
				//4. 응답페이지(deptList.jsp)로 응답 위임(전가)처리
				request.getRequestDispatcher("fullnameList.jsp").forward(request, response);
	} @Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

}

0개의 댓글