<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Jsp&Servlet Page</title>
<link rel="stylesheet" type="text/css" href="SampleServlet.css"/>
</head>
<body>
<h1>Java Web Jsp&Servlet</h1>
<br />
<a href="/SampleServlet/Insert">Entry</a><br />
<a href="/SampleServlet/Search">Search</a><br />
<a href="/SampleServlet/Select">Show AllData</a>
</body>
</html>
package sample.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SqliteDB {
// データベースとのコネクションの結果を返すオブジェクトを作成。(インターフェイス)
Connection con = null;
// SQL文を実行し、作成された結果を返すために使用されるオブジェクトを作成。(インターフェイス)
Statement stmt = null;
// SQLクエリーの実行結果を返すオブジェクトを作成。
// ResultSetにはクエリーの条件を満たす行が含まれる。(インターフェイス)
ResultSet rs = null;
// オープン
public void open() throws SQLException, ClassNotFoundException {
try {
Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException e) {
System.out.println("Sqlite JDBC Driver Error : " + e);
throw e;
}
try {
// Sqliteはデータベースファイルの存在を自動的に確認し、存在しない場合は作成します。
con = DriverManager.getConnection("jdbc:sqlite:C:/SQLite/example.DB");
stmt = con.createStatement();
stmt.executeUpdate("CREATE TABLE IF NOT EXISTS exampleTbl (id INTEGER PRIMARY KEY,name text, address text, email text, phone_number text, memo text, created_at timestamp NOT NULL default (datetime(CURRENT_TIMESTAMP,'localtime')), updated_at timestamp NOT NULL default (datetime(CURRENT_TIMESTAMP,'localtime')))");
} catch (SQLException e) {
System.out.println("Connection Error : " + e);
throw e;
}
}
// クローズ
public void descon() throws SQLException {
try {
if (con != null){
con.close();
}
} catch (Exception e) {
throw e;
}
}
// 検索
public ResultSet executeQuery(String sql) throws SQLException {
if (stmt != null){
try {
rs = stmt.executeQuery(sql);
} catch (SQLException e) {
System.out.println("executeQuery Error : " + e);
throw e;
}
}
return rs;
}
// 追加、更新、削除
public int executeUpdate(String sql) throws SQLException {
int num = 0;
if(stmt != null){
try {
con.setAutoCommit(false);
num = stmt.executeUpdate(sql);
con.commit();
} catch (SQLException e) {
try {
con.rollback();
} catch (SQLException el) {
throw el;
} finally {
if (stmt != null) {
stmt.close();
}
descon();
}
}
}
return num;
}
}
package sample.view;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import sample.util.SqliteDB;
public class Select extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void selectRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, ClassNotFoundException, SQLException {
// 日本語文字化け対策
request.setCharacterEncoding("UTF-8");
// htmlファイル形式へ出力の設定
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
// SqliteDBクラスのインスタンス作成
SqliteDB db = new SqliteDB();
// SQL文の実行結果を返すオブジェクトの定義
ResultSet rs = null;
// 全データを取得するSQL文
String sql = "SELECT * FROM exampleTbl";
String tempHtml = "";
try {
// DBのオープン
db.open();
// SQLクエリーの結果を返す
rs = db.executeQuery(sql);
// 全データを変数へ格納
while (rs.next()) {
tempHtml += "<tr>";
tempHtml += "<td>" + rs.getInt("id") + "</td>";
tempHtml += "<td>" + rs.getString("name") + "</td>";
tempHtml += "<td>" + rs.getString("address") + "</td>";
tempHtml += "<td>" + rs.getString("email") + "</td>";
tempHtml += "<td>" + rs.getString("phone_number") + "</td>";
tempHtml += "<td>" + rs.getString("memo") + "</td>";
tempHtml += "<td>" + rs.getString("created_at") + "</td>";
tempHtml += "<td>" + rs.getString("updated_at") + "</td>";
tempHtml += "<td><a href='Update?upparam=" + rs.getInt("id") + "'>Edit</a></td>";
tempHtml += "<td><a href='Delete?delparam=" + rs.getInt("id") + "' onclick=\"return deleteConfirm(" + rs.getInt("id") + ");\">Delete</a></td>";
tempHtml += "</tr>";
}
} catch (SQLException e) {
System.out.println("executeQuery Error : " + e);
throw e;
} finally {
if (rs != null) {
rs.close();
}
// コネクションのクローズ
db.descon();
}
// htmlの作成
out.println("<html>");
out.println("<head>");
out.println("<title>Jsp & Servlet - Sample Sqlite DB : datatableを扱う</title>");
out.println("<link rel=\"stylesheet\" href=\"https://cdn.datatables.net/v/bs4-4.1.1/jq-3.3.1/dt-1.10.18/sl-1.2.6/datatables.min.css\" />");
out.println("<script src=\"http://code.jquery.com/jquery-1.11.3.min.js\" ></script>");
out.println("<script src=\"https://cdn.datatables.net/v/bs4-4.1.1/jq-3.3.1/dt-1.10.18/sl-1.2.6/datatables.min.js\" ></script>");
out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"SampleServlet.css\" />");
out.println("</head>");
out.println("<body>");
out.println("<h1>Show AllData </h1>");
out.println("<br />");
out.println("<table id=\"example\" class=\"table table-striped table-bordered nowrap\" width=\"100%\">");
out.println("<thead>");
out.println("<tr>");
out.println("<th>ID</th>");
out.println("<th>NAME</th>");
out.println("<th>ADDRESS</th>");
out.println("<th>EMAIL</th>");
out.println("<th>TEL</th>");
out.println("<th>MEMO</th>");
out.println("<th>CREATED</th>");
out.println("<th>UPDATED</th>");
out.println("<th style=\"background:#dedede;\"> </th>");
out.println("<th style=\"background:#dedede;\"> </th>");
out.println("</tr>");
out.println("</thead>");
out.println("<tbody>");
out.println(tempHtml);
out.println("</tbody>");
out.println("</table>");
out.println("<br />");
out.println("<a href=\"Insert\">Entry</a><br />");
out.println("<a href=\"Search\">Search</a><br />");
out.println("<a href=\"index.jsp\">Index</a>");
out.println("<br /><br />");
// datatable Menu
out.println("<script type=\"text/javascript\">"
+"$(document).ready(function() {"
+"var table = $('#example').DataTable( {"
+"\"lengthMenu\":[[5, 10, 25, 50, -1], [5, 10, 25, 50, \"All\"]]"
+"});"
+"});"
+"</script>");
// 削除確認ダイアログ
out.println("<script type=\"text/javascript\">"
+"function deleteConfirm (id) {"
+"var id;"
+"var flag = confirm('[ '+id+' ]番のデータを削除します。間違いなければ[OK]ボタンを押して下さ。');"
+"return flag;"
+"}"
+"</script>");
out.println("</body>");
out.println("</html>");
}
// このページにGETでアクセス
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
selectRequest(request, response);
} catch (ServletException | IOException | ClassNotFoundException | SQLException e) {
Logger.getLogger(Select.class.getName()).log(Level.SEVERE, null, e);
}
}
}