[구디아카데미][IT국비지원] 4주차 동적 쿼리 활용하여 정렬하여 출력하기

띵거니·2023년 4월 26일

동적 쿼리를 활용해서 데이터 정렬하여 출력하기

쿼리문 넣을 변수를 String으로 변수 설정하고 변수 값에 order by 부분에 원하는 변수 명을 받아와서 넣어주면 쿼리문 실행할때 하나의 문장으로 만들어서 실행한다.

String sql = "select emp_no empNo, birth_date birthDate, first_name firstName, last_name lastName, gender, hire_date hireDate from employees order by "
					+ col
					+ " "
					+ ascDesc
					+ " limit ?, ?";

속성값을 클릭하면 오름차순 내림차순 변환되게 프로그램을 짰고 페이지를 변환하여도 order by 한 값이 유지되도록 fix 변수를 이용해서 asc, desc 바뀌는 걸 if문활용해서 분기해주었다.

같은 속성값을 클릭할때 만 asc, desc를 바뀌게 할려고 test 변수에 col값을 넣어서 서로 다르면 asc로 같으면 desc로 바꾸게 해두었다.

<%@page import="java.time.Year"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import = "java.sql.*" %>
<%@ page import = "java.util.*" %>
<%@ page import = "vo.*" %>
<%
	int currentPage = 1;

	if (request.getParameter("currentPage") != null) {
		currentPage = Integer.parseInt(request.getParameter("currentPage"));
	}
	
	// db 연동
	Class.forName("org.mariadb.jdbc.Driver");
	Connection conn = DriverManager.getConnection(
			"jdbc:mariadb://127.0.0.1:3306/employees", "root", "java1234");
	
	// 정렬 분기 짜기
	String col = request.getParameter("col");
	if(col == null
			|| col.equals("")){
		col = "emp_no";
	}
	
	String ascDesc = request.getParameter("ascDesc");
	if(ascDesc == null
			|| ascDesc.equals("")) {
		ascDesc = "desc";
	}
	
	String fix = request.getParameter("fix");
	if (fix == null
			|| fix.equals("")){
		fix = "0";
	}
	
	// test는 현재 페이지의 col값을 가져가기 때문에 제목을 눌렀을때 같은 제목을 눌러야만 col값과 test값이 같다.
	String test = request.getParameter("test");
	if (test == null
			|| test.equals("")){
		test = "emp_no";
	}
		
	System.out.println(col + " <-test");
	System.out.println(test + " <-test");
	// fix가 0일때 ascDesc 봐뀜 fix가 0일때 안바뀜
	if (fix.equals("0")) {
		// test와 col 값이 같을때 바뀜 아닐경우 asc로 다시 시작
		if (test.equals(col)){
			if (ascDesc.equals("asc")){
				ascDesc = "desc";
			} else {
				ascDesc = "asc";
			}
		} else {
			ascDesc = "asc";
	}
	}
	
	// 쿼리문 짜기
	String sql = "select emp_no empNo, birth_date birthDate, first_name firstName, last_name lastName, gender, hire_date hireDate from employees order by "
					+ col
					+ " "
					+ ascDesc
					+ " limit ?, ?";
	
	// 한페이지 나타내는량 변수 설정
	int pagePerView = 10;
	int limitStart = (currentPage - 1) * pagePerView;
	
	PreparedStatement stmt = conn.prepareStatement(sql);
	stmt.setInt(1, limitStart);
	stmt.setInt(2, pagePerView);
	
	System.out.println(stmt + " <- empList stmt");
	ResultSet rs = stmt.executeQuery();
	System.out.println(rs + " <- empList rs");
	
	// 마지막 페이지로 가기위한 limitEnd변수
	
	String sql2 = "SELECT COUNT(*) FROM employees";
	PreparedStatement stmt2 = conn.prepareStatement(sql2);
	ResultSet rs2 = stmt2.executeQuery();
	int limitEnd = 0;
	if(rs2.next()){
		limitEnd = rs2.getInt("count(*)");
	}
	
	System.out.println(limitEnd + " <- limitEnd");
	int lastPage = (int)Math.ceil((double)limitEnd / pagePerView);
	System.out.println(lastPage + " <- lastPage");
	
	// Empoyees 에 ArrayList로 해서 집어넣기
	ArrayList<Employees> empListArray = new ArrayList<Employees>(); 
	while (rs.next()){
		Employees e = new Employees();
		e.empNo = rs.getInt("empNo");
		e.birthDate = rs.getString("birthDate");
		e.firstName = rs.getString("firstName");
		e.lastName = rs.getString("lastName");
		e.gender = rs.getString("gender");
		e.hireDate = rs.getString("hireDate");
		empListArray.add(e);
	}
	
	// calendar API이용해서 나이구하기
	Calendar today = Calendar.getInstance();
	int todayYear = today.get(Calendar.YEAR);
	int todayMonth = today.get(Calendar.MONTH);
	int todayDate = today.get(Calendar.DATE);
	
	for (Employees e : empListArray){
	int birthYear = Integer.parseInt(e.birthDate.substring(0, 4));
	int birthMonth = Integer.parseInt(e.birthDate.substring(5, 7));
	int birthDate = Integer.parseInt(e.birthDate.substring(8));
	e.empAge = todayYear - birthYear;
		
		// 월이 같다면 날짜 비교해서 일에서 birthDate가 크면 -1
		if (birthMonth == todayMonth) {
			if (birthDate > todayDate) {
				e.empAge--;
			}
		// 월 비교해서 birthMonth가 크다면 -1
		} else if (birthMonth > todayMonth){
			e.empAge--;
		}
	}
	
%>
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>Insert title here</title>
	<link id="theme" rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
</head>
<body>
<h1>employeesList</h1>
	<!-- 데이터 출력부 -->
	<table class="table table-striped">
		<tr>
			<th>
				<a href="./empList.jsp?currentPage=<%=currentPage%>&col=emp_no&ascDesc=<%=ascDesc%>&fix=0&test=<%=col%>">
					emp_no
				</a>
			</th>
			<th>
				<a href="./empList.jsp?currentPage=<%=currentPage%>&col=birth_date&ascDesc=<%=ascDesc%>&fix=0&test=<%=col%>">
					empAge
				</a>
			</th>
			<th>
				<a href="./empList.jsp?currentPage=<%=currentPage%>&col=first_name&ascDesc=<%=ascDesc%>&fix=0&test=<%=col%>">
					first_name
				</a>
			</th>
			<th>
				<a href="./empList.jsp?currentPage=<%=currentPage%>&col=last_name&ascDesc=<%=ascDesc%>&fix=0&test=<%=col%>">
					last_name
				</a>
			</th>
			<th>
				<a href="./empList.jsp?currentPage=<%=currentPage%>&col=gender&ascDesc=<%=ascDesc%>&fix=0&test=<%=col%>">
					gender
				</a>
			</th>
			<th>
				<a href="./empList.jsp?currentPage=<%=currentPage%>&col=hire_date&ascDesc=<%=ascDesc%>&fix=0&test=<%=col%>">
					hire_date
				</a>
			</th>
		</tr>
		<%
			for (Employees e : empListArray){
		%>
				<tr>
					<td>
						<%=e.empNo%>
					</td>
					<td>
						<%=e.empAge%>
					</td>
					<td>
						<%=e.firstName%>
					</td>
					<td>
						<%=e.lastName%>
					</td>
					<td>
					<%
						if (e.gender.equals("F")){
					%>
						<img src="./img/female.jpg" height="15" width="15">
					<%
						} else {
					%>
						<img src="./img/male.jpg" height="15" width="15">
					<%
						}
					%>
					</td>
					<td>
						<%=e.hireDate%>
					</td>
				</tr>
		<%
			}
		%>
	</table>
	<!-- 페이징 출력부 -->
	<table class="table">
		<tr>
		<%
			// 필요 변수 설정
			// 페이징 시작 변수
			int startPageNum = ((currentPage - 1) / 10) * 10 + 1;
			
			// 이전 페이징으로 넘기는 변수
			int beforePage = startPageNum - 1;
			if (beforePage < 1){
				beforePage = 1;
			}
			
			// 다음 페이징으로 넘기는 변수 및 페이징 마지막 페이지 나타내는 변수
			int endPageNum = startPageNum + 10;
			if (endPageNum >= lastPage) {
				endPageNum = lastPage + 1;
			}
			
			if (currentPage > 1) {
		%>
				<td>
					<a href="./empList.jsp?currentPage=<%=1%>&col=<%=col%>&ascDesc=<%=ascDesc%>&fix=1">
						첫 페이지로
					</a>
				</td>
		<%
				// currentPage 값이 음수가 되지 않게 하기위해 나눴음
				if (currentPage > 10){
					
		%>
				<td>
					<a href="./empList.jsp?currentPage=<%=beforePage%>&col=<%=col%>&ascDesc=<%=ascDesc%>&fix=1">
						이전
					</a>
				</td>
		<%
				}
			} else {
		%>
				<td>
					첫 페이지
				</td>
		<%
			}
			
			for(int i = startPageNum; i < endPageNum; i++){
			String bgColor = null;
				if (currentPage == i) {
					bgColor = "orange";
				}
		%>
				<!-- 페이징 -->
			<td style = "background-color : <%=bgColor%>;">
				<a href="./empList.jsp?currentPage=<%=i%>&col=<%=col%>&ascDesc=<%=ascDesc%>&fix=1">
					<%=i%>
				</a>
			</td>
		<%
			}
			if (currentPage < lastPage){
				// currentPage 값이 lastPage를 넘지 않게끔 하였음
				// lastPage % 10 만큼 뺀 이유는 페이징의 마지막이 10개 이하이기때문에 하였음
				if (currentPage < (lastPage - (lastPage % 10) + 1)) {
		%>
				<td>
					<a href="./empList.jsp?currentPage=<%=endPageNum%>&col=<%=col%>&ascDesc=<%=ascDesc%>&fix=1">
						다음
					</a>
				</td>
		<%
				}
		%>
				<td>
					<a href="./empList.jsp?currentPage=<%=lastPage%>&col=<%=col%>&ascDesc=<%=ascDesc%>&fix=1">
						마지막 페이지로
					</a>
				</td>
		<%
			} else {
		%>
				<td>
					마지막 페이지
				</td>
		<%
			}
		%>
		</tr>
	</table>
</body>
</html>
profile
발효 중인 국비생

0개의 댓글