サーバーサイドにJavaを利用しMySQLからデータを取得し一覧表示する処理のサンプル
[作成]
1.MySQLでデータベース[lunchapp]を作成する。
1 | CREATE DATABASE lunchapp |
2 | DEFAULT CHARACTER SET utf8; |
2.データベースlunchappに[lunches]テーブルを作成する。
2 | id INT PRIMARY KEY AUTO_INCREMENT, |
3.初期データを挿入しておく
1 | INSERT INTO lunches(name,menu)VALUES |
2 | ("subway","チリチキン"),("はなまる","かけうどん(小)"),("吉野家","牛丼(並)") |
;
4.エクリプス。新規動的プロジェクトより「lunchapp」を作成する。
4_1.以下のリンクからjdbcをダウンロード(5.1.47)
https://downloads.mysql.com/archives/c-j/

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/lunchapp" |
09 | connectionProperties = "autoReconnect=true;verifyServerCertificate=false;useSSL=false;requireSSL=false;useUnicode=true;characterEncoding=UTF-8;" |
12 | validationQuery = "select 1" /> |
6.modelパッケージにLunch.javaを作成する。
●model.Lunch.java
03 | import java.io.Serializable; |
05 | public class Lunch implements Serializable{ |
10 | public Lunch(String name,String menu) { |
14 | public Lunch( int id,String name,String menu) { |
21 | public void setId( int id) { |
24 | public String getName() { |
27 | public void setName(String name) { |
30 | public String getMenu() { |
33 | public void setMenu(String menu) { |
「dao作成」
7.daoパッケージ内にLunchDAO.javaを作成する。
●dao.LunchDAO.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 LunchDAO { |
018 | private Connection db; |
019 | private PreparedStatement ps; |
020 | private ResultSet rs; |
023 | private void connect() throws NamingException, SQLException { |
024 | Context context = new InitialContext(); |
025 | DataSource ds = (DataSource) context.lookup( "java:comp/env/jdbc/jsp" ); |
026 | this .db = ds.getConnection(); |
030 | private void disconnect() { |
041 | } catch (SQLException e) { |
046 | public List<Lunch> findAll() { |
047 | List<Lunch> list = new ArrayList<>(); |
050 | ps = db.prepareStatement( "SELECT * FROM lunches" ); |
051 | rs = ps.executeQuery(); |
053 | int id = rs.getInt( "id" ); |
054 | String name = rs.getString( "name" ); |
055 | String menu = rs.getString( "menu" ); |
056 | Lunch l = new Lunch(id, name, menu); |
059 | } catch (NamingException | SQLException e) { |
068 | public void insertOne(Lunch lunch) { |
071 | ps=db.prepareStatement( "INSERT INTO lunches(name,menu) VALUES(?,?)" ); |
072 | ps.setString( 1 ,lunch.getName()); |
073 | ps.setString( 2 ,lunch.getMenu()); |
075 | } catch (NamingException | SQLException e) { |
081 | public Lunch findOne( int id) { |
085 | ps=db.prepareStatement( "SELECT * FROM lunches WHERE id=?" ); |
087 | rs=ps.executeQuery(); |
089 | String name=rs.getString( "name" ); |
090 | String menu=rs.getString( "menu" ); |
091 | lunch= new Lunch(id,name,menu); |
093 | } catch (NamingException | SQLException e) { |
101 | public void updateOne(Lunch lunch) { |
104 | ps=db.prepareStatement( "UPDATE lunches SET name=?,menu=? WHERE id=?" ); |
105 | ps.setString( 1 , lunch.getName()); |
106 | ps.setString( 2 , lunch.getMenu()); |
107 | ps.setInt( 3 , lunch.getId()); |
109 | } catch (NamingException | SQLException e) { |
115 | public void deleteOne( int id) { |
118 | ps=db.prepareStatement( "DELETE FROM lunches WHERE id=?" ); |
121 | } 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 | LunchDAO dao= new LunchDAO(); |
22 | List<Lunch> 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" |
02 | pageEncoding= "UTF-8" import = "model.*,java.util.*" %> |
04 | List<Lunch> list=(List<Lunch>)request.getAttribute( "list" ); |
10 | <title>Insert title here</title> |
13 | <a href= "/lunchapp/Create" >新規追加</a> |
14 | <% if (list != null && list.size()> 0 ){ %> |
16 | <tr><th>id</th><th>name</th><th>menu</th><th></th></tr> |
17 | <% for (Lunch lunch:list){ %> |
19 | <td><%=lunch.getId() %></td> |
20 | <td><%=lunch.getName() %></td> |
21 | <td><%=lunch.getMenu() %></td> |
23 | <a href= "/lunchapp/Update?id=<%=lunch.getId() %>" >更新</a> |
24 | <a href= "/lunchapp/Delete?id=<%=lunch.getId() %>" onclick= "return confirm('id=<%=lunch.getId()%>を削除してよろしいですか?');" >削除</a> |
[実行]
サーブレット(Read)から実行してみよう。以下のように表示されれば成功だ。

インサート
10.controllerパッケージ内にCreate.java(Servlet)を作成
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 | * Servlet implementation class Create |
19 | public class Create extends HttpServlet { |
20 | private static final long serialVersionUID = 1L; |
23 | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { |
24 | RequestDispatcher rd=request.getRequestDispatcher( "/WEB-INF/view/create.jsp" ); |
25 | rd.forward(request, response); |
29 | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { |
30 | request.setCharacterEncoding( "UTF-8" ); |
31 | String name=request.getParameter( "name" ); |
32 | String menu=request.getParameter( "menu" ); |
33 | Lunch lunch= new Lunch(name,menu); |
34 | LunchDAO ld= new LunchDAO(); |
37 | response.sendRedirect( "/lunchapp/Read" ); |
11./WEB-INF/viewフォルダにcreate.jspを作成
●create.jsp(/WEB-INF/view/create.jsp)
01 | <%@ page language= "java" contentType= "text/html; charset=UTF-8" |
02 | pageEncoding= "UTF-8" %> |
07 | <title>Insert title here</title> |
10 | <form action= "/lunchapp/Create" method= "post" > |
11 | なまえ:<input type= "text" name= "name" ><br> |
12 | メニュー:<input type= "text" name= "menu" ><br> |
13 | <button type= "submit" >追加</button> |
アップデート
12.controllerパッケージ内にUpdate.java(Servlet)を作成
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; |
15 | * Servlet implementation class Update |
18 | public class Update extends HttpServlet { |
19 | private static final long serialVersionUID = 1L; |
22 | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { |
23 | String s_id=request.getParameter( "id" ); |
25 | response.sendRedirect( "/lunchapp/Read" ); |
27 | LunchDAO dao= new LunchDAO(); |
28 | Lunch lunch=dao.findOne(Integer.parseInt(s_id)); |
29 | request.setAttribute( "lunch" , lunch); |
30 | request.getRequestDispatcher( "/WEB-INF/view/update.jsp" ).forward(request, response); |
34 | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { |
35 | request.setCharacterEncoding( "UTF-8" ); |
36 | String id=request.getParameter( "id" ); |
37 | String name=request.getParameter( "name" ); |
38 | String menu=request.getParameter( "menu" ); |
39 | Lunch lunch= new Lunch(Integer.parseInt(id),name,menu); |
40 | LunchDAO dao= new LunchDAO(); |
42 | response.sendRedirect( "/lunchapp/Read" ); |
13./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.*,java.util.*" %> |
04 | Lunch lunch=(Lunch)request.getAttribute( "lunch" ); |
10 | <title>Insert title here</title> |
13 | <form action= "/lunchapp/Update" method= "Post" > |
14 | なまえ:<input type= "text" name= "name" value= "<%=lunch.getName()%>" ><br> |
15 | メニュー:<input type= "text" name= "menu" value= "<%=lunch.getMenu() %>" ><br> |
16 | <input type= "hidden" name= "id" value= "<%=lunch.getId() %>" > |
17 | <button type= "submit" >更新</button> |
DELETE
14.controllerパッケージ内にDelete.java(Servlet)を作成
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 | * Servlet implementation class Delete |
17 | public class Delete extends HttpServlet { |
18 | private static final long serialVersionUID = 1L; |
21 | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { |
22 | String id=request.getParameter( "id" ); |
24 | LunchDAO dao= new LunchDAO(); |
25 | dao.deleteOne(Integer.parseInt(id)); |
27 | response.sendRedirect( "/lunchapp/Read" ); |
コメント