64
1 サーブレットとデータベースの結合 IS04 システム・組込み Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only.

サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

1

サーブレットとデータベースの結合

IS04 システム・組込み

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 2: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

2

MySQL のインストール

http://dev.mysql.com/downloads/

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 3: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

3

個人情報入力後

ダブルクリック

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 4: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

4

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 5: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

5

以前にインストールされているとき

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 6: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

6

パスワードを忘れないように(例)1234

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 7: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

7

runnning

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 8: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

8

Java との接続

C:\Program Files\MySQL\Connector J 5.1.20.0

mysql-connector-java-5.1.20-bin.jar を Eclipse の WEB-INF/lib にコピーする

XAMPP でインストールした人は、MySQL の web サイトから取得してください

http://dev.mysql.com/downloads/connector/j/

mysql-connector-java-5.1.22.zip を解凍

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 9: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

9

Eclipse の WEB-INF/lib にコピーする

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 10: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

10

クライアントからの接続

コマンドプロンプトの場合

C:\Users\IT College>cd C:\Program Files\MySQL\MySQL Server 5.5\bin

C:\Program Files\MySQL\MySQL Server 5.5\bin>mysql -u root -p

Enter password: ****

Welcome to the MySQL monitor. Commands end with ; or \g.

Your MySQL connection id is 11

Server version: 5.5.28 MySQL Community Server (GPL)

Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its

affiliates. Other names may be trademarks of their respective

owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show databases;

+--------------------+

| Database |

+--------------------+

| information_schema |

| mysql |

| performance_schema |

| test |

+--------------------+

6 rows in set (0.00 sec)

mysql>

コマンドプロンプトは SJIS にしか対応していなかったような気がします

インストール先

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 11: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

11

スタートボタン-MySQL -MySQL Workbench5.2CE

ここに SQL を記述する

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 12: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

12

Java と MySQL との接続実験

サーブレット

import java.io.IOException;

import java.io.PrintWriter;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.Statement;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class DBConnect extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

try {

Class.forName("com.mysql.jdbc.Driver");

String host =

"jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=utf8";

String user="root";

String pass="1234";

Connection con = DriverManager.getConnection(host , user , pass);

Statement statement = con.createStatement();

//切断

con.close();

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

response.setContentType("text/html");

PrintWriter out = response.getWriter();

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 13: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

13

out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");

out.println("<html>");

out.println(" <head>");

out.println(" <title>A Servlet in GET</title>");

out.println(" </head>");

out.println(" <body>");

out.println("connection OK");

out.println(" </body>");

out.println("</html>");

out.flush();

out.close();

}

}

次のようなテーブルを作成し、データを挿入

use test;

create table user(

id char(5) primary key,

name text

);

insert into user values('001' , 'IS04-1');

insert into user values('002' , 'IS04-2');

日本語もうまくいくでしょうか・・・?

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 14: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

14

import java.io.IOException;

import java.io.PrintWriter;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.ArrayList;

import java.util.List;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class DBConnect extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

String userData="NG";

List<String> names = new ArrayList<String>();

try {

Class.forName("com.mysql.jdbc.Driver");

String host =

"jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=utf8";

String user="root";

String pass="1234";

Connection con = DriverManager.getConnection(host , user , pass);

Statement statement = con.createStatement();

String sql = "select * from user";

ResultSet resultset = statement.executeQuery(sql);

while(resultset.next()){

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 15: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

15

names.add(resultset.getString("name"));

}

//切断

con.close();

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

response.setContentType("text/html;charset=utf-8");

PrintWriter out = response.getWriter();

out.println("<!DOCTYPE HTML PUBLIC ¥"-//W3C//DTD HTML 4.01 Transitional//EN¥">");

out.println("<html>");

out.println(" <head>");

out.println(" <title>A Servlet in GET</title>");

out.println(" </head>");

out.println(" <body>");

out.println("connection OK<br>");

for(int i = 0; i < names.size(); i++){

out.println("氏名"+i + ":" + names.get(i) + "<br>");

}

out.println(" </body>");

out.println("</html>");

out.flush();

out.close();

}

}

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 16: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

16

データベースとの接続メソッド

SQL の発行

クラス 戻り値の型 メソッド名 備考

Statement ResultSet executeQuery(String SQL) SELECT 文の場合

Statement int executeUpdate(String SQL) SELECT 文以外

結果の取得

SELECT 文でデータを取得したとき、ResultSet インターフェイスのオブジェクトは、抽

出されたレコードに対してポインタの働きをします。

SQL を実行した直後は、先頭のレコードの前を指します

resultset

レコード1

レコード2

レコード3

ResultSet インターフェイスの next()を実行すると、次のレコードを指すようになります

resultset レコード1

レコード2

レコード3

レコードを移動するメソッド

クラス 戻り値の型 メソッド名 動作

ResultSet boolean next() 次のレコードに移動

ResultSet boolean previous() 1つ前のレコードに移動

ResultSet boolean absolute(int row) 指定の行数に移動

ResultSet boolean relative(int rows) 相対行だけ移動

ResultSet boolean beforeFirst() 先頭のレコードより前に移動

ResultSet boolean afterLast() 最後のレコードの次に移動

ResultSet boolean first() 先頭のレコードに移動

ResultSet boolean last() 最後のレコードに移動

移動した先にレコードがあり、値が呼び出せる場合は true、読み出せない場合は false が返

ります

ResultSet がレコードを指しているとき、そのフィールドの値を取得するには、フィールド

の型ごとに異なります。

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 17: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

17

フィールドからのデータの取り出し

クラス 戻り値の型 メソッド名 動作

ResultSet int getInt(“フィールド名”)

getInt(列番号)

int 型のデータを取り出す

ResultSet long getLong(“フィールド名”)

getLong(列番号)

long 型のデータを取り出す

ResultSet double getDouble(“フィールド名”)

getDouble(列番号)

double 型のデータを取り出す

ResultSet String getString(“フィールド名”)

getString(列番号)

String 型のデータを取り出す

データベース接続 Bean

データベースとの接続は Bean にしてカプセル化します

例)会議室予約

create database yoyaku;

use yoyaku;

create table room(

id int primary key,

name char(6) not null,

max int not null

);

insert into room values(1 , "30617" , 50);

insert into room values(2 , "30705A" , 20);

insert into room values(3 , "30705B" , 30);

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 18: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

18

接続 bean

package database;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import datas.RoomData;

import datas.RoomDataList;

public class YoyakuDB {

private Connection con = null;

private ResultSet resultset = null;

private Statement statement = null;

//コンストラクタ

public YoyakuDB() throws ClassNotFoundException, SQLException {

//ドライバのロード

Class.forName("com.mysql.jdbc.Driver");

System.out.println("driver OK");

//RDBへの接続

String host=

"jdbc:mysql://localhost/yoyaku?useUnicode=true&characterEncoding=utf8";

String user="root";

String pass="1234";

con = DriverManager.getConnection(host , user , pass);

System.out.println("connection OK");

statement = con.createStatement();

System.out.println("statement OK");

}

//データの読み込み

public RoomDataList getRoomDatas() throws SQLException{

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 19: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

19

RoomDataList list = new RoomDataList();

String sql = "select * from room";

resultset = statement.executeQuery(sql);

while(resultset.next()){

RoomData data = new RoomData(resultset.getInt("id") ,

resultset.getString("name") , resultset.getInt("max"));

list.add(data);

}

return list;

}

}

data bean

package datas;

public class RoomData {

private int id;

private String name; //部屋番号

private int max; //収容最大人数

//コンストラクタ

public RoomData(int id, String name, int max) {

this.id = id;

this.name = name;

this.max = max;

}

//セッタ・ゲッタ

public RoomData() {

}

public int getId() {

return id;

}

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 20: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

20

public void setId(int id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public int getMax() {

return max;

}

public void setMax(int max) {

this.max = max;

}

}

data list bean

package datas;

import java.util.ArrayList;

import java.util.List;

public class RoomDataList {

private List<RoomData> roomList;

//コンストラクタ

public RoomDataList() {

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 21: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

21

roomList = new ArrayList<RoomData>();

}

//セッタ・ゲッタ

public List<RoomData> getRoomList() {

return roomList;

}

public void setRoomList(List<RoomData> roomList) {

this.roomList = roomList;

}

//データの追加

public void add(RoomData data){

roomList.add(data);

}

}

サーブレット

import java.io.IOException;

import java.io.PrintWriter;

import java.sql.SQLException;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import database.YoyakuDB;

import datas.RoomData;

import datas.RoomDataList;

public class DispRoomList extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 22: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

22

throws ServletException, IOException {

RoomDataList list;

try {

YoyakuDB db = new YoyakuDB();

list = db.getRoomDatas();

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

list = new RoomDataList();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

list = new RoomDataList();

}

response.setContentType("text/html;charset=utf-8");

PrintWriter out = response.getWriter();

out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");

out.println("<html>");

out.println(" <head>");

out.println(" <title>A Servlet in GET</title>");

out.println(" </head>");

out.println(" <body>");

for(RoomData roomData : list.getRoomList()){

out.println(roomData.getName() + "<br>");

}

out.println(" </body>");

out.println("</html>");

out.flush();

out.close();

}

}

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 23: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

23

データを JSP に引き継いで表示してみましょう

サーブレット

import java.io.IOException;

import java.io.PrintWriter;

import java.sql.SQLException;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import database.YoyakuDB;

import datas.RoomData;

import datas.RoomDataList;

public class DispRoomList extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

RoomDataList list = null;

try {

YoyakuDB db = new YoyakuDB();

list = db.getRoomDatas();

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

list = new RoomDataList();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

list = new RoomDataList();

}

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 24: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

24

request.setAttribute("datas", list);

this.getServletContext().getRequestDispatcher("/dispRoom.jsp").

forward(request, response);

}

}

JSP 側

<%@ page language="java" import="java.lang.*,java.util.*"

contentType="text/html;charset=utf-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<title>My JSP 'dispRoom.jsp' starting page</title>

<meta http-equiv="Pragma" content="no-cache">

<meta http-equiv="Cache-Control" content="no-cache">

<meta http-equiv="Expires" content="0">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

</head>

<body>

<jsp:useBean id="datas" class="datas.RoomDataList" scope="request"/>

<table border="1">

<tr>

<th>id</th>

<th>部屋番号</th>

<th>最大収容人数</th>

</tr>

<c:forEach var="data" items="${datas.roomList}">

<tr>

<td><c:out value="${data.id}" /></td>

<td><c:out value="${data.name}" /></td>

<td><c:out value="${data.max}" /></td>

</tr>

</c:forEach>

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 25: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

25

</table>

</body>

</html>

サーブレットを介さずに、いきなり JSP ですべてを記述することもできます。メソッド名

を getXXX( )にすることがポイントです

<%@ page language="java" import="java.lang.*,java.util.*"

contentType="text/html;charset=utf-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<title>My JSP 'dispRoom.jsp' starting page</title>

<meta http-equiv="Pragma" content="no-cache">

<meta http-equiv="Cache-Control" content="no-cache">

<meta http-equiv="Expires" content="0">

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

<meta http-equiv="description" content="This is my page">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<!--

<link rel="stylesheet" type="text/css" href="styles.css">

-->

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 26: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

26

</head>

<body>

<jsp:useBean id="db" class="database.YoyakuDB" scope="request"/>

<table border="1">

<tr>

<th>id</th>

<th>部屋番号</th>

<th>最大収容人数</th>

</tr>

<c:forEach var="data" items="${db.roomDatas.roomList}">

<tr>

<td><c:out value="${data.id}" /></td>

<td><c:out value="${data.name}" /></td>

<td><c:out value="${data.max}" /></td>

</tr>

</c:forEach>

</table>

</body>

</html>

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 27: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

27

データの挿入

予約を受け付けてみましょう

いきなりJSPで書く前に、HTMLでプロトタイプを作成しておきましょう

<%@ page language="java" import="java.lang.*,java.util.*"

contentType="text/html;charset=utf-8" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<title>予約受付</title>

<meta http-equiv="Pragma" content="no-cache">

<meta http-equiv="Cache-Control" content="no-cache">

<meta http-equiv="Expires" content="0">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

</head>

<body>

<h2>予約受付</h2>

<form action="servlet/GetYoyaku" method="post">

部屋:<select name="room">

<option value="1">30615</option>

<option value="2">30715A</option>

<option value="3">30715B</option>

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 28: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

28

</select><br>

時間枠:<select name="timezone">

<option value="1" >午前</option>

<option value="2" >午後</option>

<option value="3" >夜間</option>

</select><br>

会議名:<input type="text" name="name" ><br>

代表者:<input type="text" name="user" ><br>

<input type="submit" value="予約する"><br>

</form>

</body>

</html>

部屋を選択するリストボックスをデータベースから読み込んで表示しましょう

<jsp:useBean id="db" class="database.YoyakuDB" scope="request"/>

<h2>予約受付</h2>

部屋:<select name="room">

<c:forEach var="data" items="${db.roomDatas.roomList}">

<option value="<c:out value="${data.id}" />">

<c:out value="${data.name}" /></option>

</c:forEach>

</select><br>

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 29: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

29

受け付けた情報をデータベースに保存します

テーブルはどうしましょうか?

データベース仕様書

テーブル名:reserve

フィールド名 型 内容 備考

id int 予約番号 主キー auto_increment

roomID int 部屋番号 not null

timezone int 時間帯 not null

kaigi text 会議名

username text 代表者名

create table reserve(

id int auto_increment primary key,

roomID int not null,

timezone int not null,

kaigi text,

userName text

);

insert into reserve values(0,1,2,'連絡会議','中西');

受け取ったデータからデータを挿入するためのSQL文を組み立ててみましょう

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 30: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

30

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class GetYoyaku extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

int room = Integer.parseInt(request.getParameter("room"));

int timezone = Integer.parseInt(request.getParameter("timezone"));

String name = request.getParameter("name");

name = new String(name.getBytes("iso-8859-1") , "utf-8");

String user = request.getParameter("user");

user = new String(user.getBytes("iso-8859-1") , "utf-8");

String sql =

"insert into reserve values(0,"+room+","+timezone+",'"+name+"','"+user+"')";

response.setContentType("text/html;charset=utf-8");

PrintWriter out = response.getWriter();

out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");

out.println("<html>");

out.println(" <head>");

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 31: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

31

out.println(" <title>A Servlet in POST</title>");

out.println(" </head>");

out.println(" <body>");

out.println(sql+"<br>");

out.println(" </body>");

out.println("</html>");

out.flush();

out.close();

}

}

データベースに挿入してみます

yoyakuDB.java

//予約データの挿入

public int setReserveData(String sql) throws SQLException{

return statement.executeUpdate(sql);

}

import java.io.IOException;

import java.io.PrintWriter;

import java.sql.SQLException;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import database.YoyakuDB;

public class GetYoyaku extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

int room = Integer.parseInt(request.getParameter("room"));

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 32: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

32

int timezone = Integer.parseInt(request.getParameter("timezone"));

String name = request.getParameter("name");

name = new String(name.getBytes("iso-8859-1") , "utf-8");

String user = request.getParameter("user");

user = new String(user.getBytes("iso-8859-1") , "utf-8");

String sql

= "insert into reserve values(0,"+room+","+timezone+",'"+name+"','"+user+"')";

boolean insertResult = true;

try {

YoyakuDB db = new YoyakuDB();

db.setReserveData(sql);

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

insertResult = false;

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

insertResult = false;

}

response.setContentType("text/html;charset=utf-8");

PrintWriter out = response.getWriter();

out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");

out.println("<html>");

out.println(" <head>");

out.println(" <title>A Servlet in POST</title>");

out.println(" </head>");

out.println(" <body>");

out.println(sql+"<br>");

if(insertResult){

out.println("挿入できました");

}

else{

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 33: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

33

out.println("挿入できませんでした");

}

out.println(" </body>");

out.println("</html>");

out.flush();

out.close();

}

}

SQL の組み立ては、非常にややこしくて、間違えやすい!

String sql

= "insert into reserve values(0,"+room+","+timezone+",'"+name+"','"+user+"')";

そこで・・・

PreparedStatementクラスでは、変数にしたいところを「?」にしておいて、後で、内容を

設定します。

例)

String sql = "insert into reserve values(0,?,?,?,?)";

PreparedStatement prepStmt = con.prepareStatement(sql);

prepStmt.setInt(1,room);

prepStmt.setInt(2,timezone);

prepStmt.setString(3,name);

prepStmt.setString(4,user);

SQL の発行は今までどおり

prepStmt.executeUpdate();

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 34: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

34

YoyakuDB.java

//予約データの挿入

public int setReserveData(String sql) throws SQLException{

return statement.executeUpdate(sql);

}

public int setReserveData(int room , int timezone , String name , String user)

throws SQLException{

String sql = "insert into reserve values(0,?,?,?,?)";

PreparedStatement prepStmt = con.prepareStatement(sql);

prepStmt.setInt(1,room);

prepStmt.setInt(2,timezone);

prepStmt.setString(3,name);

prepStmt.setString(4,user);

return prepStmt.executeUpdate();

}

サーブレット

import java.io.IOException;

import java.io.PrintWriter;

import java.sql.SQLException;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import database.YoyakuDB;

public class GetYoyaku extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

int room = Integer.parseInt(request.getParameter("room"));

int timezone = Integer.parseInt(request.getParameter("timezone"));

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 35: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

35

String name = request.getParameter("name");

name = new String(name.getBytes("iso-8859-1") , "utf-8");

String user = request.getParameter("user");

user = new String(user.getBytes("iso-8859-1") , "utf-8");

boolean insertResult = true;

try {

YoyakuDB db = new YoyakuDB();

//db.setReserveData(sql);

db.setReserveData(room, timezone, name, user);

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

insertResult = false;

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

insertResult = false;

}

response.setContentType("text/html;charset=utf-8");

PrintWriter out = response.getWriter();

out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");

out.println("<html>");

out.println(" <head>");

out.println(" <title>A Servlet in POST</title>");

out.println(" </head>");

out.println(" <body>");

//out.println(sql+"<br>");

if(insertResult){

out.println("挿入できました");

}

else{

out.println("挿入できませんでした");

}

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 36: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

36

out.println(" </body>");

out.println("</html>");

out.flush();

out.close();

}

}

予約情報をクラスにしておきましょう

public int setReserveData(int room , int timezone , String name , String user)

ここをクラスのインスタンスで書き換えられる

予約情報をクラスにする

package datas;

public class YoyakuData {

private int id; //主キー

private int room; //部屋番号

private int timezone; //時間帯

private String name; //会議名

private String user; //代表者

//コンストラクタ

//主キーは挿入時点ではまだ決定していないので引数からはずしています

//後で、決定したらセッタで挿入します

public YoyakuData(int room, int timezone, String name , String user) {

this.room = room;

this.timezone = timezone;

this.name = name;

this.user = user;

}

public YoyakuData() {

}

//セッタ・ゲッタ <<略>>

}

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 37: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

37

サーブレット

import java.io.IOException;

import java.io.PrintWriter;

import java.sql.SQLException;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import database.YoyakuDB;

import datas.YoyakuData;

public class GetYoyaku extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

int room = Integer.parseInt(request.getParameter("room"));

int timezone = Integer.parseInt(request.getParameter("timezone"));

String name = request.getParameter("name");

name = new String(name.getBytes("iso-8859-1") , "utf-8");

String user = request.getParameter("user");

user = new String(user.getBytes("iso-8859-1") , "utf-8");

YoyakuData data = new YoyakuData(room , timezone , name, user);

boolean insertResult = true;

try {

YoyakuDB db = new YoyakuDB();

//db.setReserveData(sql);

//db.setReserveData(room, timezone, name, user);

db.setReserveData(data);

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

insertResult = false;

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 38: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

38

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

insertResult = false;

}

<<以下略>>

}

YoyakuDB.java に以下を追加

public int setReserveData(YoyakuData data) throws SQLException{

String sql = "insert into reserve values(0,?,?,?,?)";

PreparedStatement prepStmt = con.prepareStatement(sql);

prepStmt.setInt(1,data.getRoom());

prepStmt.setInt(2,data.getTimezone());

prepStmt.setString(3,data.getName());

prepStmt.setString(4,data.getUser());

return prepStmt.executeUpdate(); //挿入SQL発行

}

予約状況を表示したい。重なった予約は「ない」ものとする

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 39: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

39

1 行分を組にしておく。表示レイアウトは JSP 側で自在に変更してもらい、データの組み

立ては、サーブレット側で実装すると、作業の分担ができます。

部屋ごとの Bean

package datas;

public class YoyakuSet {

private int room; //部屋番号

private String roomName;//部屋名

private YoyakuData am; //午前データ

private YoyakuData pm; //午後データ

private YoyakuData night;//夜データ

//コンストラクタ

public YoyakuSet(int room , String roomName) {

this.room = room;

this.roomName = roomName;

this.am = null;

this.pm = null;

this.night = null;

}

public YoyakuSet() {

}

//セッタ・ゲッタ

<< 略 >>

}

ここをクラス(bean)にする

さらにリストにする

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 40: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

40

部屋番号(int 型)をキーとする連想配列に入れる

1 部屋の名前

30617

午前の予約

連絡会議

午後の予約

null

夜の予約

null

2 部屋の名前

30705A

午前の予約

null

午後の予約

サーブレット

夜の予約

null

3 部屋の名前

30705B

午前の予約

null

午後の予約

マナー講座

夜の予約

null

4 部屋の名前

30713

午前の予約

null

午後の予約

null

夜の予約

null

リスト

package datas;

import java.util.HashMap;

import java.util.Map;

public class YoyakuSetList {

public Map<Integer , YoyakuSet> list;

//コンストラクタ

public YoyakuSetList() {

list = new HashMap<Integer , YoyakuSet>();

}

//セッタ・ゲッタ

public Map<Integer, YoyakuSet> getList() {

return list;

}

public void setList(Map<Integer, YoyakuSet> list) {

this.list = list;

}

//部屋データ追加

public void add(int room , String roomName){

YoyakuSet set = new YoyakuSet(room , roomName);

list.put(room, set);

}

//予約データの追加

public void add(YoyakuData data){

//該当する部屋番号の予約セットを読み出す

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 41: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

41

YoyakuSet set = list.get(data.getRoom());

//予約セットの該当する時間帯にインスタンスを挿入

if(data.getTimezone() == YoyakuData.TIMEZONE_AM){

set.setAm(data);

}

else if(data.getTimezone() == YoyakuData.TIMEZONE_PM){

set.setPm(data);

}

else{

set.setNight(data);

}

}

}

YoyakuDB.java

//予約データの読み出し

public YoyakuSetList getYoyakuSetList() throws SQLException{

YoyakuSetList list = new YoyakuSetList();

String sql = "select * from room";

resultSet = statement.executeQuery(sql);

while(resultSet.next()){

int id = resultSet.getInt("id");

String roomName = resultSet.getString("name");

list.add(id , roomName);

}

sql = "select * from reserve";

resultSet = statement.executeQuery(sql);

while(resultSet.next()){

int id = resultSet.getInt("id");

int room = resultSet.getInt("roomID");

int timezone = resultSet.getInt("timezone");

String name = resultSet.getString("kaigi");

String user = resultSet.getString("userName");

YoyakuData yoyakuData =

new YoyakuData(id , room , timezone , name , user);

list.add(yoyakuData);

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 42: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

42

}

return list;

}

JSP で表示

<%@ page language="java" import="java.lang.*,java.util.*"

contentType="text/html;charset=utf-8" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<title>予約状況</title>

<meta http-equiv="Pragma" content="no-cache">

<meta http-equiv="Cache-Control" content="no-cache">

<meta http-equiv="Expires" content="0">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<style>

<!--

table{

border-collapse:collapse;

}

td,th{

padding:5px;

border-style:solid;

border-color:#0033FF;

border-width:1px;

}

-->

</style>

</head>

<body>

<jsp:useBean id="db" class="database.YoyakuDB" scope="request"/>

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 43: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

43

<h2>予約状況</h2>

<table>

<tr>

<th>部屋番号</th>

<th>午前</th>

<th>午後</th>

<th>夜間</th>

</tr>

<c:forEach var="set" items="${db.yoyakuSetList.list}">

<tr>

<td><c:out value="${set.value.roomName}" /></td>

<td><c:out value="${set.value.am.name}" /><br>

<c:out value="${set.value.am.user}" /></td>

<td><c:out value="${set.value.pm.name}" /><br>

<c:out value="${set.value.pm.user}" /></td>

<td><c:out value="${set.value.night.name}" /><br>

<c:out value="${set.value.night.user}" /></td>

</tr>

</c:forEach>

</table>

</body>

</html>

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 44: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

44

予約と解約

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 45: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

45

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 46: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

46

予約状況のソースのうち、予約がないセルは

<td>

<form action="yoyakuRecieve.jsp" method="post" >

<input type="hidden" name="roomName" value="30617" >

<input type="hidden" name="room" value="1" >

<input type="hidden" name="timezone" value="1" >

<input type="hidden" name="timezoneName" value="午前" >

<input type="submit" value="予約">

</form>

</td>

予約があるセルは

<td>

<form action="servlet/YoyakuCancell" method="post" >

成績判定会議(中西)</br>

<input type="submit" value="解約">

<input type="hidden" name="id" value="13" >

</form>

</td>

yoyakuState.jsp

<%@ page language="java" import="java.lang.*,java.util.*"

contentType="text/html;charset=utf-8" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<title>予約状況</title>

<meta http-equiv="Pragma" content="no-cache">

<meta http-equiv="Cache-Control" content="no-cache">

<meta http-equiv="Expires" content="0">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<style>

<!--

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 47: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

47

table{

border-collapse:collapse;

}

td,th{

padding:5px;

border-style:solid;

border-color:#0033FF;

border-width:1px;

text-align:center;

}

-->

</style>

</head>

<body>

<jsp:useBean id="db" class="database.YoyakuDB" scope="request"/>

<jsp:setProperty property="today" name="db" value="2012-12-19"/>

<jsp:useBean id="today" class="date.Today" scope="request" />

<h2>予約状況(<c:out value="${ today.string}" />)</h2>

<table>

<tr>

<th>部屋番号</th>

<th>午前</th>

<th>午後</th>

<th>夜間</th>

</tr>

<c:forEach var="set" items="${db.yoyakuSetList.list}">

<tr>

<td><c:out value="${set.value.roomName}" /></td>

<td>

<c:choose>

<c:when test="${set.value.am != null}">

<form action="servlet/YoyakuCancell" method="post" >

<c:out value="${set.value.am.name}" />

(<c:out value="${set.value.am.user}" />)</br>

<input type="submit" value="解約">

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 48: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

48

<input type="hidden" name="id"

value="<c:out value="${set.value.am.id}" />" >

</form>

</c:when>

<c:otherwise>

<form action="yoyakuRecieve.jsp" method="post" >

<input type="hidden" name="roomName"

value="<c:out value="${set.value.roomName}" />" >

<input type="hidden" name="room"

value="<c:out value="${set.key}" />" >

<input type="hidden" name="timezone" value="1" >

<input type="hidden" name="timezoneName" value="午前" >

<input type="submit" value="予約">

</form>

</c:otherwise>

</c:choose>

</td>

<td>

<c:choose>

<c:when test="${set.value.pm != null}">

<form action="servlet/YoyakuCancell" method="post" >

<c:out value="${set.value.pm.name}" />

(<c:out value="${set.value.pm.user}" />)</br>

<input type="submit" value="解約">

<input type="hidden" name="id"

value="<c:out value="${set.value.pm.id}" />" >

</form>

</c:when>

<c:otherwise>

<form action="yoyakuRecieve.jsp" method="post" >

<input type="hidden" name="roomName"

value="<c:out value="${set.value.roomName}" />" >

<input type="hidden" name="room"

value="<c:out value="${set.key}" />" >

<input type="hidden" name="timezone" value="2" >

<input type="hidden" name="timezoneName" value="午後" >

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 49: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

49

<input type="submit" value="予約">

</form>

</c:otherwise>

</c:choose>

</td>

<td>

<c:choose>

<c:when test="${set.value.night != null}">

<form action="servlet/YoyakuCancell" method="post" >

<c:out value="${set.value.night.name}" />

(<c:out value="${set.value.night.user}" />)</br>

<input type="submit" value="解約">

<input type="hidden" name="id"

value="<c:out value="${set.value.night.id}" />" >

</form>

</c:when>

<c:otherwise>

<form action="yoyakuRecieve.jsp" method="post" >

<input type="hidden" name="roomName"

value="<c:out value="${set.value.roomName}" />" >

<input type="hidden" name="room"

value="<c:out value="${set.key}" />" >

<input type="hidden" name="timezone" value="3" >

<input type="hidden" name="timezoneName" value="夜間" >

<input type="submit" value="予約">

</form>

</c:otherwise>

</c:choose>

</td>

</tr>

</c:forEach>

</table>

</body>

</html>

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 50: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

50

予約受付処理

送られてくるパラメータを受け取る Bean を作成。それをもとに予約受付画面の JSP を表

示する

Bean

package datas;

import java.io.UnsupportedEncodingException;

public class RecieveParam {

private int room; //部屋番号

private String roomName; //部屋名

private int timezone; //時間帯

private String timezoneName;//時間帯の名前

//コンストラクタ

public RecieveParam() {

}

//セッタ・ゲッタ

<<略>>

}

受付画面

<%@ page language="java" import="java.lang.*,java.util.*"

contentType="text/html;charset=utf-8" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<title>予約受付</title>

<meta http-equiv="Pragma" content="no-cache">

<meta http-equiv="Cache-Control" content="no-cache">

<meta http-equiv="Expires" content="0">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 51: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

51

</head>

<body>

<jsp:useBean id="paramData" class="datas.RecieveParam" scope="request" />

<jsp:setProperty name="paramData" property="*" />

<h2>予約受付</h2>

<form action="servlet/GetYoyaku" method="post" >

部屋番号:<c:out value="${paramData.roomName}" /><br>

時間帯:<c:out value="${ paramData.timezoneName}" /><br>

会議名:<input type="text" name="name"><br>

代表者名:<input type="text" name="user"><br>

<input type="hidden" name="timezone" value="<c:out value="${ paramData.timezone}" />">

<input type="hidden" name="room" value="<c:out value="${ paramData.room }" />">

<input type="submit" value="予約" >

</form>

</body>

</html>

予約サーブレットに遷移する

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 52: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

52

キャンセル処理

データベースから削除する

YoyakuDB.java

//予約データの削除

public int deleteYoyaku(int id) throws SQLException{

String sql = "delete from reserve where id=?";

PreparedStatement prepStmt = con.prepareStatement(sql);

prepStmt.setInt(1,id);

return prepStmt.executeUpdate();

}

削除するサーブレット

import java.io.IOException;

import java.io.PrintWriter;

import java.sql.SQLException;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import database.YoyakuDB;

public class YoyakuCancell extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

int id = Integer.parseInt(request.getParameter("id")); //予約番号

boolean flg = true;

try {

YoyakuDB db = new YoyakuDB();

if(db.deleteYoyaku(id) != 1){

flg = false;

}

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 53: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

53

flg = false;

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

flg = false;

}

response.setContentType("text/html; charset=utf-8");

PrintWriter out = response.getWriter();

out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");

out.println("<html>");

out.println(" <head>");

out.println(" <title>キャンセル</title>");

out.println(" </head>");

out.println(" <body>");

if(flg){

out.println("キャンセルしました");

}

else{

out.println("キャンセルできませんでした");

}

out.println(" </body>");

out.println("</html>");

out.flush();

out.close();

}

}

本来は、削除してしまうのではなく、データベースに「有効/無効」フラグを付け、「無効」

になるように更新することをおすすめします。一度保存されたデータは、削除されても、

履歴として何等かの形で残しておくことが必要です

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 54: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

54

画面のつながり

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 55: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

55

こんな風につながりたいけど・・・・サーブレットをはさむと URL に「servlet/」が付い

てしまってうまくつながらない

サーブレットに「servlet/」が付かなければいいじゃないか!

web.xml

<servlet-mapping>

<servlet-name>GetYoyaku</servlet-name>

<url-pattern>/GetYoyaku</url-pattern>

</servlet-mapping>

yoyakuRecieve.jsp

<form action="GetYoyaku" method="post" >

GetYoyaku.java

import java.io.IOException;

import java.io.PrintWriter;

import java.sql.SQLException;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import database.YoyakuDB;

import datas.YoyakuData;

public class GetYoyaku extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

int room = Integer.parseInt(request.getParameter("room"));

int timezone = Integer.parseInt(request.getParameter("timezone"));

String name = request.getParameter("name");

name = new String(name.getBytes("iso-8859-1") , "utf-8");

String user = request.getParameter("user");

user = new String(user.getBytes("iso-8859-1") , "utf-8");

//String sql

= "insert into reserve values(0,"+room+","+timezone+",'"+name+"','"+user+"')";

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 56: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

56

YoyakuData data = new YoyakuData(room , timezone , name, user);

boolean insertResult = true;

try {

YoyakuDB db = new YoyakuDB();

//db.setReserveData(sql);

//db.setReserveData(room, timezone, name, user);

db.setReserveData(data);

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

insertResult = false;

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

insertResult = false;

}

if(insertResult){

this.getServletContext().getRequestDispatcher("/YoyakuState.jsp").

forward(request, response);

}

else{

response.setContentType("text/html;charset=utf-8");

PrintWriter out = response.getWriter();

out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");

out.println("<html>");

out.println(" <head>");

out.println(" <title>A Servlet in POST</title>");

out.println(" </head>");

out.println(" <body>");

out.println("挿入できませんでした");

out.println(" </body>");

out.println("</html>");

out.flush();

out.close();

}

}

}

もちろん、キャンセルも同様です

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 57: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

57

サーブレットを生成するとき

URL に/servlet を抜けば、/servlet なしの XML が生成されます

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 58: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

58

日付の取り扱い

日付は案外厄介です。大の月、小の月、うるう年まであります。Java では Date クラスで

一手に引き受けてくれています

現在時刻の取得

Date オブジェクト名 = Calendar.getInstance().getTime();

Date クラスは、1900 年 1 月 1 日午前 0 時 0 分を 0 として、ミリ秒を積算した値を持ちま

す。これをいわゆる「日付」の形式に変換するには、SimpleDateFormat を使います

SimpleDateFormat dateFormat = new SimpleDateFotmat(“形式”);

String s = dateFormat.format(date));

主な変換記号

文字 意味 例 文字 意味 例

G 紀元 AD HH 時(24 時間制) 23

yyyy 年 2012 hh 時(12 時間制) 02

MM 月 01 mm 分 59

dd 日 30 ss 秒 27

E 曜日 金 a 午前・午後 PM

例)

SimpleDateFormat dateFormat = new SimpleDateFotmat(“yyyy.MM.dd’(‘ E ‘)’”);

2012 年 12 月 19 日(水)

となります

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 59: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

59

日付を表示する

date.Today.java

package date;

import java.text.DateFormat;

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.Calendar;

import java.util.Date;

public class Today {

private Date today;

public static String f = "yyyy-MM-dd";

//コンストラクタ

public Today(Date today) {

this.today = today;

}

public Today() {

this.today = Calendar.getInstance().getTime(); //現在の日付と時刻

}

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 60: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

60

public Today(String s) throws ParseException{

DateFormat dateFormat = new SimpleDateFormat(f);

today = dateFormat.parse(s);

}

//セッタ・ゲッタ

public Date getToday() {

return today;

}

public void setToday(Date today) {

this.today = today;

}

//文字列にする

public String getString() {

SimpleDateFormat dateFormat = new SimpleDateFormat(f);

return dateFormat.format(today);

}

}

YoyakuState.jsp

<body>

<jsp:useBean id="db" class="database.YoyakuDB" scope="request"/>

<jsp:useBean id="today" class="date.Today" scope="request" />

<h2>予約状況(<c:out value="${ today.string}" />)</h2>

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 61: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

61

データベースにも日付を記録するためのフィールドを作成しましょう.

MySQL には、Date 型、DateTime 型、TimeStamp 型が用意されています

データベース仕様書を書き換えます

データベース仕様書

テーブル名:reserve

フィールド名 型 内容 備考

id int 予約番号 主キー auto_increment

reserveDate date 予約日 not null

roomID int 部屋番号 not null

timezone int 時間帯 not null

kaigi text 会議名

username text 代表者名

create table reserve(

id int auto_increment primary key,

reserveDate date not null,

roomID int not null,

timezone int not null,

kaigi text,

userName text

);

insert into reserve values(0,'2012-12-19' , 1,1,'連絡会議' , '中西');

Java の Date クラスと MySQL の Date とは微妙にデータが違うので、文字列でやり取りし

ます。

データベースからは、

getString(“フィールド名”);

で読み込みます。

上の段はデータベースから読み込んだもの、下の段は、Date クラスにしたもの

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 62: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

62

import java.io.IOException;

import java.io.PrintWriter;

import java.sql.SQLException;

import java.text.ParseException;

import java.util.Date;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import database.YoyakuDB;

import date.Today;

public class DateTest extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

String today = null;

Today todayDate = null;

try {

YoyakuDB db = new YoyakuDB();

today = db.getToday();

todayDate = new Today(today);

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (ParseException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

response.setContentType("text/html;charset=utf-8");

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 63: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

63

PrintWriter out = response.getWriter();

out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");

out.println("<html>");

out.println(" <head>");

out.println(" <title>A Servlet in GET</title>");

out.println(" </head>");

out.println(" <body>");

out.println("date:" + today+ "<br>");

out.println("date2:" + todayDate.getString()+ "<br>");

out.println(" </body>");

out.println("</html>");

out.flush();

out.close();

}

}

翌日を表すには、getTime()に 24*60*60*1000(ミリ秒)を加算して setTime()します

Today.java

//日付の加算

public void addDay(int day){

today.setTime(today.getTime()+day*24*60*60*1000);

}

.

DateTest.java

todayDate.addDay(1); //翌日

out.println("tomorrow:" + todayDate.getString()+ "<br>");

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.

Page 64: サーブレットとデータベースの結合tomorrow.on.coocan.jp/neec/is04/servletDB.pdf · ResultSetインターフェイスのnext()を実行すると、次のレコードを指すようになります

64

Generated by Foxit PDF Creator © Foxit Softwarehttp://www.foxitsoftware.com For evaluation only.