WEBアプリとPostgreSQLを接続
Employee.java
package model; import java.io.Serializable; public class Employee implements Serializable { private String id; private String name; private int age; public Employee(String id, String name, int age) { this.id = id; this.name = name; this.age = age; } public String getId() { return this.id; } public String getName() { return this.name; } public int getAge() { return this.age; } }
EmployeeDAO.java
package dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import model.Employee; public class EmployeeDAO { private final String JDBC_url = "jdbc:postgresql://localhost:5432/example"; private final String JDBC_user = "postgres"; private final String JDBC_pass = "password"; public List<Employee> findAll() { Connection conn = null; PreparedStatement pstmt = null; ResultSet rSet = null; List<Employee> empList = new ArrayList<Employee>(); try { Class.forName("org.postgresql.Driver"); System.out.println("データベースに接続しました"); } catch (ClassNotFoundException e) { e.printStackTrace(); } try { conn = DriverManager.getConnection(JDBC_url, JDBC_user, JDBC_pass); pstmt = conn.prepareStatement("select * from employee"); rSet = pstmt.executeQuery(); while(rSet.next()) { String id = rSet.getString("id"); String name = rSet.getString("name"); int age = rSet.getInt("age"); Employee employee = new Employee(id, name, age); empList.add(employee); } } catch (SQLException e) { e.printStackTrace(); } return empList; } }
index.jsp(配置するのはWEB-INFディレクトリ)
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="dao.EmployeeDAO,model.Employee,java.util.List,java.util.ArrayList" %> <% EmployeeDAO employeeDAO = new EmployeeDAO(); List<Employee> empList = employeeDAO.findAll(); %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>あはあ</title> </head> <body> <h1>え</h1> <% for(Employee employee : empList) { %> <p> ID:<%= employee.getId() %><br> 名前:<%= employee.getName() %><br> 年齢:<%= employee.getAge() %> </p> <% } %> </body> </html>