JAVA EE データベース利用
準備
ソース
JSP連携
package myPack;
import java.sql.ResultSet;
@WebServlet("/SelectService")
public class SelectService extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection con = null;
Statement state = null;
try{
con = DriverManager.getConnection();
state = con.createStatement();
con.setAutoCommit(false);
ResultSet result = state.executeQuery("SELECT * FROM ACCOUNT;");
List<Account> list = new ArrayList<Account>();
while(result.next()){
Account account = new Account();
account.setId(result.getInt("ID"));
account.setName(result.getString("NAME"));
account.setMoney(result.getInt("MONEY"));
list.add(account);
}
request.setAttribute("list", list);
ResultSetをListへ格納してからコネクションを閉じる
request.getRequestDispatcher("/select.jsp").forward(request, response);
}catch(Exception e){
e.printStackTrace();
}finally{
try{ state.close(); }catch(Exception e){}
try{ con.close(); }catch(Exception e){}
}
}
}
データソース
データソース利用
import javax.naming.InitialContext;
import javax.sql.DataSource;
response.setContentType("text/plain charset=UTF-8");
try{
InitialContext context = new InitialContext();
DataSource source = (DataSource) context.lookup("java:comp/env/jdbc/myds");
Connection con = source.getConnection();
}catch(Exception e){
throw new ServletException(e);
}
コンテキストファイル
<Context>
<Resource
name="jdbc/myds"
auth="Container"
type="javax.sql.DataSource"
username="sa"
password=""
driverClassName="org.hsqldb.jdbcDriver"
url="jdbc:hsqldb:hsql://localhost"/>
</Context>