그런 곳에는 Hibernate나 iBatis를 쓰기에는 너무 거창하다는 느낌이 들기도 합니다. 그렇다고 JDBC로 날코딩하기는 성가실때, 이럴 때는 apache commons DbUtils를 써볼만 합니다.
- 다운로드 : http://commons.apache.org/downloads/download_dbutils.cgi
- API 문서 : http://commons.apache.org/dbutils/apidocs/index.html
JDBC에서 Connection, Statement,ResultSet의 close 글에 나온 것처럼 Connection을 닫는 번거로운 처리가 DbUtils.closeQuietly(con);로 끝나는 것만 해도 상당히 편합니다.
아래 예제는 DBUtils + JSTL로 간단한 조회화면을 만들어 본 것입니다.
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<%@ page import = "java.sql.*" %>
<%@ page import = "java.util.Properties" %>
<%@ page import = "org.apache.commons.dbutils.DbUtils" %>
<%@ page import = "org.apache.commons.dbutils.QueryRunner" %>
<%@ page import = " org.apache.commons.dbutils.handlers.MapListHandler" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%!
private static final String SELECT_STMT =
"SELECT id, name, email, cell_phone_number FROM quiz_user";
%>
<%
String url = "jdbc:hsqldb:hsql://localhost/sampledb";
Properties prop = new Properties();
prop.put("user","sa");
prop.put("password","");
Connection con = null;
try{
Class.forName ("org.hsqldb.jdbcDriver");
con = DriverManager.getConnection(url,prop);
QueryRunner runner = new QueryRunner();
Object resultList = runner.query(con,SELECT_STMT, new MapListHandler());
request.setAttribute("list",resultList);
} catch (SQLException ex) {throw new RuntimeException(ex);
} finally {
DbUtils.closeQuietly(con);
}
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>사용자</title>
</head>
<body>
<h1>사용자 조회</h1>
<h2>사용자 목록</h2>
<table class="list">
<tr>
<th>id</th><th>이름</th><th>전화번호</th> <th>이메일</th>
</tr>
<c:forEach var="item" items="${list}" varStatus="status">
<tr>
<td>${item.id}</td>
<td align="center">${item.name}</td>
<td>${item.cell_phone_number}</td>
<td align="center">${item.email}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
몇 년전에 DbUtils와 비슷한 클래스를 만든 적이 있었는데, 그때도 좀 찾아볼 걸 그랬나봅니다. 그러고 보면 저도 apache commons에 이미 있는 것을 많이도 만들어본 삽질의 시간들을 겪었었습니다. 신입 때 commons beanutils하고 commons io에 포함된 것 비슷한 유틸리티 만들어 놓고 혼자서 뿌듯해 했었죠 -_-;