[spring] HikariCP이용하여 DB내용 읽어와서 view 만들기

Jong·2021년 10월 4일
0

java swing

목록 보기
4/4
post-thumbnail

자바관리도구인 maven에 hikariCP dependency를 등록하여 DB를 가져다 사용해서 테이블모양으로 view를 만들어 보았다.

/*
root-context.xml에다가, 
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
위 2가지import내용을 context에다가 bean 등록해서 직접 객체선언하지 않고 @Autowired어노테이션을 이용해서
가져다 쓰기 위해
*/
<beans xmlns="http://www.springframework.org/schema/beans">
	<bean id="config" class="com.zaxxer.hikari.HikariConfig">
		<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
		<property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521/XEPDB1" />
		<property name="username" value="hr" />
		<property name="password" value="1234" />
	</bean>		
	
	<bean class="com.zaxxer.hikari.HikariDataSource">
		<constructor-arg ref="config" />
	</bean>
</beans>

// Controller내용.
@Log4j
@RequestMapping("/employee")
@Controller
public class EmployeeController {

	@Autowired
	HikariDataSource ds;
	
	
	//@GetMapping("/list")
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public void list(Model model) {
		
		try(
			Connection conn = ds.getConnection();
			PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM employees");
			ResultSet rs = pstmt.executeQuery();
		) {
			
			ArrayList<Employee> list = new ArrayList<>();
			
			while(rs.next()) {
				list.add(new Employee(rs.getString("first_name"),
						rs.getString("last_name"),
						rs.getString("email"),
						rs.getDate("hire_date")
					));
			}
			
			model.addAttribute("employees", list);
		} catch (SQLException e) {
			
			e.printStackTrace();
		}
		
		
	}
}

//view페이지
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Employee List</title>
<style>
	th, td{
		border : solid black 3px;
		padding : 3px;
	}
</style>
</head>
<body>

	<table style="border-collapse:collapse;">
		<tr>
			<th>First Name</th>
			<th>Last Name</th>
			<th>Email</th>
			<th>Hire Date</th>
		</tr>
		<c:forEach var="employee" items="${employees}">
			<tr>
				<td>${employee.first_name}</td>
				<td>${employee.last_name}</td>
				<td>${employee.email}</td>
				<td>${employee.hire_date}</td>
				
			</tr>
		</c:forEach>
	</table>
</body>
</html>
  • 컴파일 결과
profile
새싹 개발자 수련중(블로그 이전)

0개의 댓글