다연이네

[days04] 해당 사원 정보 테이블로 출력, 버튼 클릭시 사원번호 넘기기 본문

JSP

[days04] 해당 사원 정보 테이블로 출력, 버튼 클릭시 사원번호 넘기기

 다연  2020. 12. 28. 20:10
반응형

흐름

ex01.jsp -> Test01.java (서블릿) -> test01.jsp -> test01_ok.jsp

 

 

 

ex01.jsp

ex01.jsp에서 밑의 태그를 클릭하면 서블릿에서 포워드 된 test01.jsp 화면으로 넘어가게 된다.

 

Test01.java  =>  test01.jsp

좌측 상단의 select를 통해 부서를 선택하면 해당 부서의 사원 정보를 모두 출력하게 된다.

* 부서는 DB를 통해 얻어왔고 4가지 부서가 존재한다.

 

특정 사원의 체크박스를 클릭한 후 [확인] 버튼을 누르게 되면 test01_ok.jsp로 넘어간다.

test01_ok.jsp

test01_ok.jsp 페이지에서는 선택된 사원들의 empno를 출력한다.

 

 

 

ex01.jsp

<body>
<a href="/jspPro/deptNemp.html">/deptNemp.html</a><br>
<a href="/jspPro/days04/test01">/jspPro/days04/test01</a><br>
</body>

Test01.java (서블릿)

Dept와 Emp를 모두 가져와야 한다.

=> deptList와 empList를 모두 얻어왔다.

package days04;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.LinkedHashMap;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.util.DBConn;

import days03.DeptDTO;
import days03.EmpDTO;

/**
 * Servlet implementation class DeptNEmp
 */
@WebServlet("/days04/test01")
public class Test01 extends HttpServlet {
   private static final long serialVersionUID = 1L;

   /**
    * @see HttpServlet#HttpServlet()
    */
   public Test01() {
      super();
      // TODO Auto-generated constructor stub
   }

   /**
    * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
    */
   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      
      String sql = "select deptno, dname, loc "
                  + " from dept"; 

      Connection con = null;
      PreparedStatement pstmt = null;
      ResultSet rs = null; 
      ArrayList<DeptDTO> deptList = null; 
       
      DeptDTO dto = null; 

      int deptno;
      String dname, loc;

      con = DBConn.getConnection();
      try {
         pstmt = con.prepareStatement(sql);
         rs = pstmt.executeQuery();          

         if (rs.next()) {
            deptList = new ArrayList<DeptDTO>();
            do {
                  deptno =  rs.getInt("deptno");   
                  dname =  rs.getString("dname");  
                  loc = rs.getString("loc");       
               dto = new DeptDTO(deptno, dname, loc); 
 
               deptList.add(dto);
             } while (rs.next());
         } // if
      } catch (SQLException e) { 
         e.printStackTrace();
      } finally {
         try {
            rs.close();
            pstmt.close(); 
         } catch (SQLException e) {
            e.printStackTrace();
         }
      }// try
      
       
      ArrayList<EmpDTO> empList = null;
      
      String pDeptno = request.getParameter("deptno");
      deptno =pDeptno==null? 10:Integer.parseInt(pDeptno); 
      //넘어오는 값 없음 기본 값 10
      
      sql = "select empno, ename, job, mgr, hiredate, sal, comm, deptno "
            + " from emp "
            +" where deptno = ?" ;
      try {
         pstmt = con.prepareStatement(sql);
         pstmt.setInt(1,  deptno);
         rs = pstmt.executeQuery();
         EmpDTO empDto = null;

         if (rs.next()) {
            empList = new ArrayList<EmpDTO>();
            do {
               empDto = new EmpDTO( rs.getInt("empno")
                                                 , rs.getString("ename")
                                                 , rs.getString("job")
                                                 , rs.getInt("mgr")
                                                 , rs.getDate("hiredate")
                                                 , rs.getDouble("sal")
                                                 , rs.getDouble("comm")
                                                 , rs.getInt("deptno"));       
 
               empList.add(empDto);
             } while (rs.next());
         } // if
      } catch (SQLException e) { 
         e.printStackTrace();
      } finally {
         try {
            rs.close();
            pstmt.close();
            DBConn.close();
         } catch (SQLException e) {
            e.printStackTrace();
         }
      }// try
      
      // 
      request.setAttribute("deptList", deptList);
      request.setAttribute("empList", empList);
      // Forward
      String path = "/days04/test01.jsp";
      RequestDispatcher dispatcher =request.getRequestDispatcher(path);
      dispatcher.forward(request, response);
   } // doGet

   /**
    * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    */
   protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      doGet(request, response);
   }

}

 

test01.jsp

<%@page import="days03.DeptDTO"%>
<%@page import="java.util.ArrayList"%>
<%@ page 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>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="">
<style>
table{
	width: 100%;
}
table, th, td{
	border: 1px solid gray;
}

</style>
<script>
   $(document).ready(function (){   
   		//select로 부서 선택시 부서번호 달아서 url 수정
	   $("#deptno").change(function(event) {
	   		location.href="/jspPro/days04/test01?deptno="+$(this).val(); 
	   });
	   
       //체크박스 가운데 정렬
	   //tbody tr 첫번째 td
	  // $("table tbody tr td:first-child").css({
	   $("table tbody tr").find("td:first-child").css({
		   //backgroundColor: "yellow",
		   textAlign: "center"
	   });
	   
		//select 초기값 10, 선택시 그 값 유지
	  $("#deptno").val("${empty param.deptno ? 10 : param.deptno}"); //쌍따옴표 필수
	  //EL 안에서도 삼항 연산자가 사용 가능하다
	
	  //test01_ok.jsp로 넘기기
	  $("#checked_empno").on("click", function(event) {
		  //?deptno=7499&deptno=7698 &...
			var deptnos = [];
		  
		  //jQuery에서만 사용하는 선택자 :checked (체크된 체크박스를 가져오는 선택자)
		  //jQuery 메소드 - each (하나하나 돌겠다)	
		  $("table tbody :checked").each(function(i, element) {
		  		var deptno = $(this).parent().next().html();
		  		//console.log(deptno);
		  		//체크박스의 부모의 다음 형제 노드 ==td.html()
		  		deptnos.push(deptno);
		  		//alert(deptnos.join("&deptno="));
		  	});
		  	
	  		location.href="/jspPro/days04/test01_ok.jsp?deptno="+deptnos.join("&deptno=");
	  });
      
	  //체크박스 전체선택
	  $("#ckbAll").change(function(event) {
		   $("table tbody tr").find("td:first-child :checkbox")
           		.prop("checked", $(this).prop("checked"));
	   });
   });
</script>
</head>
<body>
<select name="deptno" id="deptno">
	<c:forEach items="${deptList }" var="dto">
		<option value="${dto.deptno }">${dto.dname}</option>
	</c:forEach>
</select>
<p></p>
<!-- table>thead>tr>th*9 -->
<table>
	<thead>
		<tr>
			<th><input type="checkbox" id="ckbAll" name="ckbAll" />전체선택</th>
			<th>empno</th>
			<th>ename</th>
			<th>job</th>
			<th>mgr</th>
			<th>hiredate</th>
			<th>sal</th>
			<th>comm</th>
			<th>deptno</th>
		</tr>
	</thead>
	<tbody>
		<!-- tr>td*9 -->
		<c:choose>
			<c:when test="${not empty empList }">
				<c:forEach items="${empList }" var="eDto">
					<tr>
					 <td><input type="checkbox"  value="${eDto.empno}" name=""/></td>
					 <!--<td style="text-align: center;">  체크박스 가운데 정렬-->
					 <td>${eDto.empno}</td>
					 <td>${eDto.ename }</td>
					 <td>${eDto.job }</td>
					 <td>${eDto.mgr }</td>
					 <td>${eDto.hiredate}</td>
					 <td>${eDto.sal}</td>
					 <td>${eDto.comm}</td>
					 <td>${eDto.deptno}</td>
					</tr>
				</c:forEach>
			</c:when>
			<c:otherwise>
				<tr>
					<td colspan="9">사원 존재 않음</td>
				</tr>
			</c:otherwise>
		</c:choose>
		
	</tbody>
	<tfoot>
		<tr>
			<td colspan="9" style="text-align: center;">
				<button id="checked_empno">확인</button>
			</td>
		</tr>
	</tfoot>
</table>
</body>
</html>

 

test01_ok.jsp

<%@page import="org.apache.jasper.tagplugins.jstl.core.ForEach"%>
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="">
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<style>
</style>
<script>
   $(document).ready(function (){     
   });
</script>
</head>
<body>

<%
String [] deptnoArray = request.getParameterValues("deptno");
%>
<%
	for(int i=0;i<deptnoArray.length; i++){
%>
<%=deptnoArray[i]%>
<br>
<%
	}
%>

 <br>
 EL+JSTL 코딩
 <br>
 
 <c:set value="<%= deptnoArray.length %>" var="length"></c:set>
 몇명 선택했냐면 > ${ length }<br>
  

  <c:forEach begin="0" end="${ length-1 }" step="1" var="i">
    >${ paramValues.deptno[i] }<br>
  </c:forEach>
</body>
</html>
반응형
Comments