DAOを使って基本的なCRUDを実現しよう。今回は処理の一つ一つがわかりやすいようにファイルを分割し、装飾的要素もつけないで行う。
[作成]
1.MySQLでデータベース[personapp]を作成する。
1 | CREATE DATABASE personapp |
2 | DEFAULT CHARACTER SET utf8; |
2.データベースpersonappに[persons]テーブルを作成する。
2 | id INT PRIMARY KEY AUTO_INCREMENT, |
3.初期データを挿入しておく
1 | INSERT INTO persons(name,age)VALUES |
2 | ("John",30),("Paul",28),("George",27),("Ringo",26); |

4.エクリプス。新規動的プロジェクトより「joytas9」を作成する。
5.WEB-INF/lib/の中にJDBC,META-INFの直下にcontext.xmlを配置する。(詳しくは前回の記事参照)
01 | <? xml version = "1.0" encoding = "UTF-8" ?> |
06 | type = "javax.sql.DataSource" |
07 | driverClassName = "com.mysql.jdbc.Driver" |
08 | url = "jdbc:mysql://localhost:3306/personapp" |
09 | connectionProperties = "autoReconnect=true;verifyServerCertificate=false;useSSL=false;requireSSL=false;useUnicode=true;characterEncoding=UTF-8;" |
12 | validationQuery = "select 1" /> |
6.modelパッケージにPerson.javaを作成する。
●model.Person.java
03 | import java.io.Serializable; |
05 | public class Person implements Serializable{ |
10 | public Person(String name, int age){ |
14 | public Person( int id,String name, int age){ |
21 | public void setId( int id) { |
24 | public String getName() { |
27 | public void setName(String name) { |
33 | public void setAge( int age) { |
「Read作成」
7.daoパッケージ内にPersonDAO.javaを作成する。
●dao.PersonDAO.java
03 | import java.sql.Connection; |
04 | import java.sql.PreparedStatement; |
05 | import java.sql.ResultSet; |
06 | import java.sql.SQLException; |
07 | import java.util.ArrayList; |
10 | import javax.naming.Context; |
11 | import javax.naming.InitialContext; |
12 | import javax.naming.NamingException; |
13 | import javax.sql.DataSource; |
17 | public class PersonDAO { |
18 | private Connection db; |
19 | private PreparedStatement ps; |
22 | private void connect() throws NamingException, SQLException { |
23 | Context context = new InitialContext(); |
24 | DataSource ds = (DataSource) context.lookup( "java:comp/env/jdbc/jsp" ); |
25 | this .db = ds.getConnection(); |
28 | private void disconnect() { |
39 | } catch (SQLException e) { |
43 | public List<Person> findAll(){ |
44 | List<Person> list= new ArrayList<>(); |
47 | ps=db.prepareStatement( "SELECT * FROM persons" ); |
50 | int id=rs.getInt( "id" ); |
51 | String name=rs.getString( "name" ); |
52 | int age=rs.getInt( "age" ); |
53 | list.add( new Person(id,name,age)); |
55 | } catch (NamingException | SQLException e) { |
8.controllerパッケージ内にRead.java(Servlet)を作成
03 | import java.io.IOException; |
06 | import javax.servlet.RequestDispatcher; |
07 | import javax.servlet.ServletException; |
08 | import javax.servlet.annotation.WebServlet; |
09 | import javax.servlet.http.HttpServlet; |
10 | import javax.servlet.http.HttpServletRequest; |
11 | import javax.servlet.http.HttpServletResponse; |
17 | public class Read extends HttpServlet { |
18 | private static final long serialVersionUID = 1L; |
20 | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { |
21 | PersonDAO dao= new PersonDAO(); |
22 | List<Person> list=dao.findAll(); |
23 | request.setAttribute( "list" , list); |
24 | RequestDispatcher rd=request.getRequestDispatcher( "/WEB-INF/view/read.jsp" ); |
25 | rd.forward(request, response); |
9.WEB-INF/viewフォルダにread.jspを作成
●read.jsp(WEB-INF/view/read.jsp)
01 | <%@ page language= "java" contentType= "text/html; charset=UTF-8" pageEncoding= "UTF-8" import = "model.*,java.util.*" %> |
03 | List<Person> list=(List<Person>)request.getAttribute( "list" ); |
08 | <meta charset= "UTF-8" /> |
12 | <a href= "/joytas9/Create" >新規登録</a> |
13 | <% if (list != null && list.size() > 0 ){ %> |
16 | <% for (Person p:list){ %> |
20 | <td><%=p.getId() %></td> |
23 | <td><%=p.getName() %></td> |
26 | <td><%=p.getAge() %></td> |
29 | <td><a href= "/joytas9/Update?id=<%=p.getId()%>" >更新</a> |
30 | <a href= "/joytas9/Delete?id=<%=p.getId()%>" onclick= "return confirm('id=<%=p.getId()%>を削除してよろしいですか?');" >削除</a></td> |
10.Read.javaをサーバーで実行する。(以下のようになることを確認)

「Create作成」
11.controllerパッケージ内にCreate.javaを作成。
●controller.Create.java
03 | import java.io.IOException; |
05 | import javax.servlet.RequestDispatcher; |
06 | import javax.servlet.ServletException; |
07 | import javax.servlet.annotation.WebServlet; |
08 | import javax.servlet.http.HttpServlet; |
09 | import javax.servlet.http.HttpServletRequest; |
10 | import javax.servlet.http.HttpServletResponse; |
13 | public class Create extends HttpServlet { |
14 | private static final long serialVersionUID = 1L; |
16 | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { |
17 | RequestDispatcher rd=request.getRequestDispatcher( "/WEB-INF/view/create.jsp" ); |
18 | rd.forward(request, response); |
22 | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { |
12.WEB−INF/viewフォルダ内にcreate.jspを作成
●create.jsp(WEB-INF/view/create.jsp)
01 | <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> |
05 | <meta charset="UTF-8"/> |
10 | <form action="/joytas9/Create" method="post"> |
11 | 名前:<input type="text" name="name"><br> |
12 | 年齢:<input type="number" name="age"><br> |
13 | <button type="submit">登録</button> |
13.Create.javaを実行してみて以下のようになることを確認する。

14.フォームから入力されたデータをDBにインサートしよう。まずはPersonDAO.javaに追記する。
●dao.PersonDAO.java(62~74行追記)
03 | import java.sql.Connection; |
04 | import java.sql.PreparedStatement; |
05 | import java.sql.ResultSet; |
06 | import java.sql.SQLException; |
07 | import java.util.ArrayList; |
10 | import javax.naming.Context; |
11 | import javax.naming.InitialContext; |
12 | import javax.naming.NamingException; |
13 | import javax.sql.DataSource; |
17 | public class PersonDAO { |
18 | private Connection db; |
19 | private PreparedStatement ps; |
22 | private void connect() throws NamingException, SQLException { |
23 | Context context = new InitialContext(); |
24 | DataSource ds = (DataSource) context.lookup( "java:comp/env/jdbc/jsp" ); |
25 | this .db = ds.getConnection(); |
28 | private void disconnect() { |
39 | } catch (SQLException e) { |
43 | public List<Person> findAll(){ |
44 | List<Person> list= new ArrayList<>(); |
47 | ps=db.prepareStatement( "SELECT * FROM persons" ); |
50 | int id=rs.getInt( "id" ); |
51 | String name=rs.getString( "name" ); |
52 | int age=rs.getInt( "age" ); |
53 | list.add( new Person(id,name,age)); |
55 | } catch (NamingException | SQLException e) { |
62 | public void insertOne(Person person){ |
65 | ps=db.prepareStatement( "INSERT INTO persons(name,age) VALUES(?,?)" ); |
66 | ps.setString( 1 , person.getName()); |
67 | ps.setInt( 2 , person.getAge()); |
69 | } catch (NamingException | SQLException e) { |
15.controller.Create.javaのdoPost内に追記する。
03 | import java.io.IOException; |
05 | import javax.servlet.RequestDispatcher; |
06 | import javax.servlet.ServletException; |
07 | import javax.servlet.annotation.WebServlet; |
08 | import javax.servlet.http.HttpServlet; |
09 | import javax.servlet.http.HttpServletRequest; |
10 | import javax.servlet.http.HttpServletResponse; |
16 | public class Create extends HttpServlet { |
17 | private static final long serialVersionUID = 1L; |
19 | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { |
20 | RequestDispatcher rd=request.getRequestDispatcher( "/WEB-INF/view/create.jsp" ); |
21 | rd.forward(request, response); |
25 | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { |
26 | request.setCharacterEncoding( "UTF-8" ); |
27 | String name=request.getParameter( "name" ); |
28 | String age=request.getParameter( "age" ); |
29 | Person person= new Person(name,Integer.parseInt(age)); |
30 | PersonDAO dao= new PersonDAO(); |
31 | dao.insertOne(person); |
33 | response.sendRedirect( "/joytas9/Read" ); |
16.Create.javaから実行し、フォームにPeter,33と入れて登録ボタンを押してみよう。以下のように表示されれば成功だ。

「Update作成」
17.続いて更新処理を作っていこう。まずはPersonDAO.javaにidをもとに1件のデータを取得するfindOne()を追記する。
●dao.PersonDAO.java
03 | import java.sql.Connection; |
04 | import java.sql.PreparedStatement; |
05 | import java.sql.ResultSet; |
06 | import java.sql.SQLException; |
07 | import java.util.ArrayList; |
10 | import javax.naming.Context; |
11 | import javax.naming.InitialContext; |
12 | import javax.naming.NamingException; |
13 | import javax.sql.DataSource; |
17 | public class PersonDAO { |
18 | private Connection db; |
19 | private PreparedStatement ps; |
22 | private void connect() throws NamingException, SQLException { |
23 | Context context = new InitialContext(); |
24 | DataSource ds = (DataSource) context.lookup( "java:comp/env/jdbc/jsp" ); |
25 | this .db = ds.getConnection(); |
28 | private void disconnect() { |
39 | } catch (SQLException e) { |
43 | public List<Person> findAll(){ |
44 | List<Person> list= new ArrayList<>(); |
47 | ps=db.prepareStatement( "SELECT * FROM persons" ); |
50 | int id=rs.getInt( "id" ); |
51 | String name=rs.getString( "name" ); |
52 | int age=rs.getInt( "age" ); |
53 | list.add( new Person(id,name,age)); |
55 | } catch (NamingException | SQLException e) { |
62 | public void insertOne(Person person){ |
65 | ps=db.prepareStatement( "INSERT INTO persons(name,age) VALUES(?,?)" ); |
66 | ps.setString( 1 , person.getName()); |
67 | ps.setInt( 2 , person.getAge()); |
69 | } catch (NamingException | SQLException e) { |
76 | public Person findOne( int id){ |
80 | ps=db.prepareStatement( "SELECT * FROM persons WHERE id=?" ); |
84 | String name=rs.getString( "name" ); |
85 | int age=rs.getInt( "age" ); |
86 | person= new Person(id,name,age); |
88 | } catch (NamingException | SQLException e) { |
18.controller内にUpdate.javaを以下のように記述する。
●controller.Update.java
03 | import java.io.IOException; |
05 | import javax.servlet.RequestDispatcher; |
06 | import javax.servlet.ServletException; |
07 | import javax.servlet.annotation.WebServlet; |
08 | import javax.servlet.http.HttpServlet; |
09 | import javax.servlet.http.HttpServletRequest; |
10 | import javax.servlet.http.HttpServletResponse; |
16 | public class Update extends HttpServlet { |
17 | private static final long serialVersionUID = 1L; |
19 | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { |
20 | String s_id=request.getParameter( "id" ); |
22 | response.sendRedirect( "/joytas9/Read" ); |
24 | PersonDAO dao= new PersonDAO(); |
25 | Person person=dao.findOne(Integer.parseInt(s_id)); |
26 | request.setAttribute( "person" , person); |
27 | RequestDispatcher rd=request.getRequestDispatcher( "/WEB-INF/view/update.jsp" ); |
28 | rd.forward(request, response); |
32 | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { |
19.WEB-INF/viewの中にupdate.jspを以下のように作成する。
●update.jsp(WEB-INF/view/update.jsp)
01 | <%@ page language= "java" contentType= "text/html; charset=UTF-8" |
02 | pageEncoding= "UTF-8" import = "model.*" %> |
04 | Person person=(Person)request.getAttribute( "person" ); |
09 | <meta charset= "UTF-8" /> |
13 | <form action= "/joytas9/Update" method= "post" > |
14 | 名前:<input type= "text" name= "name" value= "<%=person.getName() %>" ><br> |
15 | 年齢:<input type= "number" name= "age" value= "<%=person.getAge() %>" ><br> |
16 | <input type= "hidden" name= "id" value= "<%=person.getId() %>" ><br> |
17 | <button type= "submit" >更新</button> |
20.Read.javaから実行し、任意のデータの更新リンクを押してみよう。以下のように情報がフォームに反映されれば成功だ。

21.更新ボタンを押したらDBの情報を更新する処理を作る。まずはPersonDAOに追記 (updateOne())
●controller.PersonDAO.java
003 | import java.sql.Connection; |
004 | import java.sql.PreparedStatement; |
005 | import java.sql.ResultSet; |
006 | import java.sql.SQLException; |
007 | import java.util.ArrayList; |
008 | import java.util.List; |
010 | import javax.naming.Context; |
011 | import javax.naming.InitialContext; |
012 | import javax.naming.NamingException; |
013 | import javax.sql.DataSource; |
017 | public class PersonDAO { |
018 | private Connection db; |
019 | private PreparedStatement ps; |
020 | private ResultSet rs; |
022 | private void connect() throws NamingException, SQLException { |
023 | Context context = new InitialContext(); |
024 | DataSource ds = (DataSource) context.lookup( "java:comp/env/jdbc/jsp" ); |
025 | this .db = ds.getConnection(); |
028 | private void disconnect() { |
039 | } catch (SQLException e) { |
043 | public List<Person> findAll(){ |
044 | List<Person> list= new ArrayList<>(); |
047 | ps=db.prepareStatement( "SELECT * FROM persons" ); |
048 | rs=ps.executeQuery(); |
050 | int id=rs.getInt( "id" ); |
051 | String name=rs.getString( "name" ); |
052 | int age=rs.getInt( "age" ); |
053 | list.add( new Person(id,name,age)); |
055 | } catch (NamingException | SQLException e) { |
062 | public void insertOne(Person person){ |
065 | ps=db.prepareStatement( "INSERT INTO persons(name,age) VALUES(?,?)" ); |
066 | ps.setString( 1 , person.getName()); |
067 | ps.setInt( 2 , person.getAge()); |
069 | } catch (NamingException | SQLException e) { |
075 | public Person findOne( int id){ |
079 | ps=db.prepareStatement( "SELECT * FROM persons WHERE id=?" ); |
081 | rs=ps.executeQuery(); |
083 | String name=rs.getString( "name" ); |
084 | int age=rs.getInt( "age" ); |
085 | person= new Person(id,name,age); |
087 | } catch (NamingException | SQLException e) { |
095 | public void updateOne(Person person){ |
098 | ps=db.prepareStatement( "UPDATE persons SET name=?,age=? WHERE id=?" ); |
099 | ps.setString( 1 , person.getName()); |
100 | ps.setInt( 2 , person.getAge()); |
101 | ps.setInt( 3 , person.getId()); |
103 | } catch (NamingException | SQLException e) { |
22.controller.Update.javaにpostの処理を追記する。
●controller.UPdate.java
03 | import java.io.IOException; |
05 | import javax.servlet.RequestDispatcher; |
06 | import javax.servlet.ServletException; |
07 | import javax.servlet.annotation.WebServlet; |
08 | import javax.servlet.http.HttpServlet; |
09 | import javax.servlet.http.HttpServletRequest; |
10 | import javax.servlet.http.HttpServletResponse; |
16 | public class Update extends HttpServlet { |
17 | private static final long serialVersionUID = 1L; |
19 | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { |
20 | String s_id=request.getParameter( "id" ); |
22 | response.sendRedirect( "/joytas9/Read" ); |
24 | PersonDAO dao= new PersonDAO(); |
25 | Person person=dao.findOne(Integer.parseInt(s_id)); |
26 | request.setAttribute( "person" , person); |
27 | RequestDispatcher rd=request.getRequestDispatcher( "/WEB-INF/view/update.jsp" ); |
28 | rd.forward(request, response); |
32 | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { |
34 | request.setCharacterEncoding( "UTF-8" ); |
35 | String name=request.getParameter( "name" ); |
36 | String age=request.getParameter( "age" ); |
37 | String id=request.getParameter( "id" ); |
38 | Person person= new Person(Integer.parseInt(id),name,Integer.parseInt(age)); |
39 | PersonDAO dao= new PersonDAO(); |
40 | dao.updateOne(person); |
42 | response.sendRedirect( "/joytas9/Read" ); |
23.情報を更新してみよう。以下のように更新が反映されれば成功だ。(Peterの年齢を34に変更した)

「Delete作成」
24.最後に削除の処理を作る。まずはPersonDAOに追記。(deleteOne())
●dao.PersonDAO.java
003 | import java.sql.Connection; |
004 | import java.sql.PreparedStatement; |
005 | import java.sql.ResultSet; |
006 | import java.sql.SQLException; |
007 | import java.util.ArrayList; |
008 | import java.util.List; |
010 | import javax.naming.Context; |
011 | import javax.naming.InitialContext; |
012 | import javax.naming.NamingException; |
013 | import javax.sql.DataSource; |
017 | public class PersonDAO { |
018 | private Connection db; |
019 | private PreparedStatement ps; |
020 | private ResultSet rs; |
022 | private void connect() throws NamingException, SQLException { |
023 | Context context = new InitialContext(); |
024 | DataSource ds = (DataSource) context.lookup( "java:comp/env/jdbc/jsp" ); |
025 | this .db = ds.getConnection(); |
028 | private void disconnect() { |
039 | } catch (SQLException e) { |
043 | public List<Person> findAll(){ |
044 | List<Person> list= new ArrayList<>(); |
047 | ps=db.prepareStatement( "SELECT * FROM persons" ); |
048 | rs=ps.executeQuery(); |
050 | int id=rs.getInt( "id" ); |
051 | String name=rs.getString( "name" ); |
052 | int age=rs.getInt( "age" ); |
053 | list.add( new Person(id,name,age)); |
055 | } catch (NamingException | SQLException e) { |
062 | public void insertOne(Person person){ |
065 | ps=db.prepareStatement( "INSERT INTO persons(name,age) VALUES(?,?)" ); |
066 | ps.setString( 1 , person.getName()); |
067 | ps.setInt( 2 , person.getAge()); |
069 | } catch (NamingException | SQLException e) { |
075 | public Person findOne( int id){ |
079 | ps=db.prepareStatement( "SELECT * FROM persons WHERE id=?" ); |
081 | rs=ps.executeQuery(); |
083 | String name=rs.getString( "name" ); |
084 | int age=rs.getInt( "age" ); |
085 | person= new Person(id,name,age); |
087 | } catch (NamingException | SQLException e) { |
095 | public void updateOne(Person person){ |
098 | ps=db.prepareStatement( "UPDATE persons SET name=?,age=? WHERE id=?" ); |
099 | ps.setString( 1 , person.getName()); |
100 | ps.setInt( 2 , person.getAge()); |
101 | ps.setInt( 3 , person.getId()); |
103 | } catch (NamingException | SQLException e) { |
110 | public void deleteOne( int id){ |
113 | ps=db.prepareStatement( "DELETE FROM persons WHERE id=?" ); |
116 | } catch (NamingException | SQLException e) { |
25.controller内にDelete.java(Servlet)を作成。
●controller.Delete.java
03 | import java.io.IOException; |
05 | import javax.servlet.ServletException; |
06 | import javax.servlet.annotation.WebServlet; |
07 | import javax.servlet.http.HttpServlet; |
08 | import javax.servlet.http.HttpServletRequest; |
09 | import javax.servlet.http.HttpServletResponse; |
14 | public class Delete extends HttpServlet { |
15 | private static final long serialVersionUID = 1L; |
17 | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { |
18 | String s_id=request.getParameter( "id" ); |
20 | PersonDAO dao= new PersonDAO(); |
21 | dao.deleteOne(Integer.parseInt(s_id)); |
23 | response.sendRedirect( "/joytas9/Read" ); |
26.Peterを削除してみよう。ダイアログが表示された後、OKで削除されれば成功だ。


コメント