Re:SALOON & VBA

JAVA使いへの道⑥

JAVA使いへの道、第⑤が最終回のつもりでしたが、
私事ではありますが、またまた、無職期間に入りました(暇がある)ので
進めて更新画面まで、実装してみました。

勿論今回も、教則となるのは、引き続き
TECHNICAL MASTER はじめてのJSP&サーブレット 第2版 Tomcat 8対応
という本です。



サンプルコードは、ダウンロードできます。
でも、やっぱり自分で書かないと勉強にはならないですが・・・。

更新ページは延長なので、載せる必要なし
みたいなことを、前回、書きましたが、
何の何の、南野陽子
やってみれば、いろいろ、上手く行かないところがあって(全部、自分のミスなんですが)
そういう躓きが勉強になるのです。やっぱり。

一覧画面


詳細画面


課題としては、デザインの調整(インプット領域の幅や、高さ)とか
画像のアップロード機能とか・・・(手作業で格納しています)
簡単なエラーチェックしかしていないので、その辺りの強化とか
ページング機能とか・・・いろいろありますね。

環境等は、本の指示するまま →DBは、前回と同じです。MySQL(MariaDB)です、tableは一切変更してません。
なので、create SQLは、今回は未記載です。
既存ソースは、ほとんど変更していませんが、あれこれ修正したり、デバッグしたりしているので
再度、まるまる載せています。

※以下のソースは、文字化け対策で例によって、インデント(空白)、"<" ">"は、全角化して掲載
 他にも化けてましたら、推測で直してください。って、使う人いないと思うけど・・・



実行は、index.jsp から

■workspace/BookLog/src/booklog/dao/BooklogDAO.java
package booklog.dao;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import booklog.entity.Booklog;
public class BooklogDAO extends DAO {
 public List<Booklog> booklogList() throws Exception {
  // 実行するSQLを作成
  String sql = "SELECT bookname, author, getdate, readdate, isbn13, state "
    + "FROM booklog order by getdate desc";
  // ステートメント(SQLを格納・実行するコンテナ)を取得。
  PreparedStatement statement = getPreparedStatement(sql);
  ResultSet rs = statement.executeQuery();
  List<Booklog> returnList = new ArrayList<Booklog>();
  while (rs.next()) {
   // 検索結果1レコードの内容を取得する
   Booklog blog = new Booklog();
   blog.setBookname(rs.getString("bookname"));
   blog.setAuthor(rs.getString("author"));
   blog.setGetdate(rs.getTimestamp("getdate"));
   blog.setReaddate(rs.getTimestamp("readdate"));
   blog.setIsbn13(rs.getString("isbn13"));
   blog.setState(rs.getInt("state"));
   // 検索結果をListへ格納
   returnList.add(blog);
  }
  return returnList;
 }
 /**
  * 表示する読書履歴のISBN13を指定して、読書履歴詳細を返す。
  * @param isbn13 表示対象のISBN13
  * @return
  * @throws Exception
  */
 public Booklog detail(String isbn13) throws Exception {
  // 実行するSQLを作成
  String sql = "SELECT isbn13, isbn10, bookname, author, publisher, genre, issuedate, getdate," +
     " readdate, ownership, purchase, library, overview, impressions, state, coverimg" +
     " FROM booklog where isbn13 = ?";
  // ステートメント(SQLを格納・実行するコンテナ)を取得。
  PreparedStatement statement = getPreparedStatement(sql);
  statement.setString(1, isbn13);
  // SQLを実行してその結果を取得する。
  ResultSet rs = statement.executeQuery();
  Booklog blog = new Booklog();
  // 検索結果の行数分フェッチを行い、取得結果をBLOGへ格納する
  while (rs.next()) {
   // クエリー結果をBLOGへ格納(あらかじめクエリー結果とBLOGの変数名は一致させている)
   blog.setIsbn13(rs.getString("isbn13"));
   blog.setIsbn10(rs.getString("isbn10"));
   blog.setBookname(rs.getString("bookname"));
   blog.setAuthor(rs.getString("author"));
   blog.setPublisher(rs.getString("publisher"));
   blog.setGenre(rs.getString("genre"));
   blog.setIssuedate(rs.getTimestamp("issuedate"));
   blog.setGetdate(rs.getTimestamp("getdate"));
   blog.setReaddate(rs.getTimestamp("readdate"));
   blog.setOwnership(rs.getInt("ownership"));
   blog.setPurchase(rs.getInt("purchase"));
   blog.setLibrary(rs.getString("library"));
   blog.setOverview(rs.getString("overview"));
   blog.setImpressions(rs.getString("impressions"));
   blog.setState(rs.getInt("state"));
   blog.setCoverimg(rs.getString("coverimg"));
  }
  return blog;
 }
 /**
  * 削除処理を行う。指定されたISBN13の読書履歴を削除する。
  * @param isbn13
  * @return 削除件数
  * @throws Exception
  */
 public int delete(String isbn13) throws Exception {
  String sql = "DELETE FROM booklog where isbn13 = ?";
  // SQLを実行してその結果を取得する。
  int result = 0;
  try {
   // プリペアステートメントを取得し、実行SQLを渡す
   PreparedStatement statement = getPreparedStatement(sql);
   statement.setString(1, isbn13);
   result = statement.executeUpdate();
   // コミットを行う
   super.commit();
  } catch (Exception e) {
   super.rollback();
   throw e;
  }
  return result;
 }
 /**
  * 新規登録処理を行う。
  * @param blog 入力された読書履歴内容。
  * @return 追加された件数
  * @throws Exception
  */
 public int registerInsert(Booklog blog) throws Exception {
  String sql = "INSERT INTO booklog (isbn13, isbn10, bookname, author, publisher, genre, issuedate," +
     " getdate, readdate, ownership, purchase, library, overview, impressions, state, coverimg)" +
     " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
  int result = 0;
  // プリペアステートメントを取得し、実行SQLを渡す
  try {
   PreparedStatement statement = getPreparedStatement(sql);
   statement.setString(1, blog.getIsbn13());
   statement.setString(2, blog.getIsbn10());
   statement.setString(3, blog.getBookname());
   statement.setString(4, blog.getAuthor());
   statement.setString(5, blog.getPublisher());
   statement.setString(6, blog.getGenre());
   statement.setString(7, blog.getInputIssuedate());
   statement.setString(8, blog.getInputGetdate());
   statement.setString(9, blog.getInputReaddate());
   statement.setInt(10, blog.getOwnership());
   statement.setInt(11, blog.getPurchase());
   statement.setString(12, blog.getLibrary());
   statement.setString(13, blog.getOverview());
   statement.setString(14, blog.getImpressions());
   statement.setInt(15, blog.getState());
   statement.setString(16, blog.getCoverimg());
   result = statement.executeUpdate();
   // コミットを行う
   super.commit();
  } catch (Exception e) {
   // ロールバックを行い、スローした例外は呼び元のクラスへ渡す
   super.rollback();
   throw e;
  }
  return result;
 }
 /**
  * 更新処理を行う。
  * @param blog
  * @return
  * @throws Exception
  */
 public int registerUpdate(Booklog blog) throws Exception {
  String sql = "UPDATE booklog SET isbn10 = ?, bookname = ?, author = ?, publisher = ?, genre = ?," +
     " issuedate = ?, getdate = ?, readdate = ?, ownership = ?, purchase = ?, library = ?," +
     " overview = ?, impressions = ?, state = ?, coverimg = ? WHERE isbn13 = ?";
  // プリペアステートメントを取得し、実行SQLを渡す
  int result =0;
  try {
   PreparedStatement statement = getPreparedStatement(sql);
   statement.setString(1, blog.getIsbn10());
   statement.setString(2, blog.getBookname());
   statement.setString(3, blog.getAuthor());
   statement.setString(4, blog.getPublisher());
   statement.setString(5, blog.getGenre());
   statement.setString(6, blog.getInputIssuedate());
   statement.setString(7, blog.getInputGetdate());
   statement.setString(8, blog.getInputReaddate());
   statement.setInt(9, blog.getOwnership());
   statement.setInt(10, blog.getPurchase());
   statement.setString(11, blog.getLibrary());
   statement.setString(12, blog.getOverview());
   statement.setString(13, blog.getImpressions());
   statement.setInt(14, blog.getState());
   statement.setString(15, blog.getCoverimg());
   statement.setString(16, blog.getIsbn13());
   result = statement.executeUpdate();
   // コミットを行う
   super.commit();
  } catch (Exception e) {
   super.rollback();
   throw e;
  }
  return result;
 }
}

■workspace/BookLog/src/booklog/dao/DAO.java
package booklog.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class DAO implements AutoCloseable {
 protected Connection connection = null;
 public DAO() {
 }
 /**
  * データベースとの接続を取得する。 もし取得していた場合には既存の接続を利用し、 取得していない場合は新たにコンテナから取得する。
  *
  * @return
  * @throws Exception
  */
 public Connection getConnection() throws Exception {
  // NamingException, SQLExceptionがスローされる
  try {
   if (connection == null || connection.isClosed()) {
    InitialContext initCtx = new InitialContext();
    DataSource ds = (DataSource) initCtx.lookup("java:comp/env/jdbc/localDB");
    // データベース接続を取得する
    connection = ds.getConnection();
   }
  } catch (NamingException|SQLException e) {
   // もし接続取得で例外が出た場合はconnection=nullにし、
   // 発生した例外はそのまま送出する。
   e.printStackTrace();
   connection = null;
   throw e;
  }
  return connection;
 }
 /**
  * 接続を閉じる。
  */
 public void close() {
  System.out.println("close connection ------------------------------------>");
  try {
   connection.close();
  } catch (SQLException e) {
   e.printStackTrace();
  } finally {
   connection = null;
  }
 }
 /**
  * PreparedStatementを返す。
  *
  * @param sql
  * @return
  * @throws Exception
  */
 public PreparedStatement getPreparedStatement(String sql) throws Exception {
  return getConnection().prepareStatement(sql);
 }
 /**
  * トランザクションのコミットを行う。
  *
  * @throws SQLException
  */
 public void commit() throws SQLException {
  connection.commit();
 }
 /**
  * トランザクションのロールバックを行う。
  *
  * @throws SQLException
  */
 public void rollback() throws SQLException {
  connection.rollback();
 }
 /**
  * 接続を閉じる。確実に接続を開放するためfinallyでconnection=nullを行う。
  */
 public void closeConnection() {
  try {
   connection.close();
  } catch (SQLException e) {
   e.printStackTrace();
  } finally {
   connection = null;
  }
 }
}

■workspace/BookLog/src/booklog/entity/Booklog.java
package booklog.entity;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
public class Booklog {
 private String isbn13;
 private String isbn10;
 private String bookname;
 private String author;
 private String publisher;
 private String genre;
 private Timestamp issuedate;
 private Timestamp getdate;
 private Timestamp readdate;
 private int ownership;
 private int purchase;
 private String library;
 private String overview;
 private String impressions;
 private Integer state;
 private String coverimg;
 private String inputIssuedate;
 private String inputGetdate;
 private String inputReaddate;
 private String mode;
 public String getIsbn13() {
  return isbn13;
 }
 public void setIsbn13(String isbn13) {
  this.isbn13 = isbn13;
 }
 public String getBookname() {
  return bookname;
 }
 public String getIsbn10() {
  return isbn10;
 }
 public void setIsbn10(String isbn10) {
  this.isbn10 = isbn10;
 }
 public void setBookname(String bookname) {
  this.bookname = bookname;
 }
 public String getAuthor() {
  return author;
 }
 public void setAuthor(String author) {
  this.author = author;
 }
 public String getPublisher() {
  return publisher;
 }
 public void setPublisher(String publisher) {
  this.publisher = publisher;
 }
 public String getGenre() {
  return genre;
 }
 public void setGenre(String genre) {
  this.genre = genre;
 }
 public Timestamp getIssuedate() {
  return issuedate;
 }
 public void setIssuedate(Timestamp issuedate) {
  this.issuedate = issuedate;
 }
 public Timestamp getGetdate() {
  return getdate;
 }
 public void setGetdate(Timestamp getdate) {
  this.getdate = getdate;
 }
 public Timestamp getReaddate() {
  return readdate;
 }
 public void setReaddate(Timestamp readdate) {
  this.readdate = readdate;
 }
 public int getOwnership() {
  return ownership;
 }
 public void setOwnership(int ownership) {
  this.ownership = ownership;
 }
 public int getPurchase() {
  return purchase;
 }
 public void setPurchase(int purchase) {
  this.purchase = purchase;
 }
 public String getLibrary() {
  return library;
 }
 public void setLibrary(String library) {
  this.library = library;
 }
 public String getOverview() {
  return overview;
 }
 public void setOverview(String overview) {
  this.overview = overview;
 }
 public String getImpressions() {
  return impressions;
 }
 public void setImpressions(String impressions) {
  this.impressions = impressions;
 }
 public Integer getState() {
  return state;
 }
 public void setState(Integer state) {
  this.state = state;
 }
 public String getCoverimg() {
  return coverimg;
 }
 public void setCoverimg(String coverimg) {
  this.coverimg = coverimg;
 }
 public String getInputIssuedate() {
  return inputIssuedate;
 }
 public void setInputIssuedate(String inputIssuedate) {
  this.inputIssuedate = inputIssuedate;
 }
 public String getInputGetdate() {
  return inputGetdate;
 }
 public void setInputGetdate(String inputGetdate) {
  this.inputGetdate = inputGetdate;
 }
 public String getInputReaddate() {
  return inputReaddate;
 }
 public void setInputReaddate(String inputReaddate) {
  this.inputReaddate = inputReaddate;
 }
 public String getMode() {
  return mode;
 }
 /**
  * 入力チェックを行う。もし入力チェックエラーがあった場合にはエラーメッセージを追加。
  */
 public boolean valueCheck() {
  // エラーメッセージの初期化
  errorMessages = new ArrayList<String>();
  // isbn13
  if (isbn13 == null || isbn13.isEmpty()) {
   errorMessages.add("ISBN13の入力がありません。");
  } else if (isbn13.length() != 13) {
   errorMessages.add("ISBN13の桁数が異なります。13桁で入力してください。");
  }
  // 書名
  if (bookname == null || bookname.isEmpty()) {
   errorMessages.add("書名の入力がありません。");
  } else if (bookname.length() > 50) {
   errorMessages.add("書名が長すぎます。50桁以内です。");
  }
  // 入手日
  if (inputGetdate == null || inputGetdate.isEmpty()) {
   errorMessages.add("入手日の入力がありません");
  } else if (!inputGetdate.matches("//d{4}-//d{2}-//d{2}")) {
   errorMessages.add("入力された入手日の日付フォーマットが異なります(YYYY-MM-DD)");
  }
  // 発行日
  if (inputIssuedate != null) {
   if (!inputIssuedate.matches("//d{4}-//d{2}-//d{2}")) {
    errorMessages.add("入力された発行日の日付フォーマットが異なります(YYYY-MM-DD)");
   }
  }
  // 読了日
  if (inputReaddate != null) {
   if (!inputReaddate.matches("//d{4}-//d{2}-//d{2}")) {
    errorMessages.add("入力された読了日の日付フォーマットが異なります(YYYY-MM-DD)");
   }
  }
  return (errorMessages.size() == 0);
 }
 private List<String> errorMessages;
 public List<String> getErrorMessages() {
  return errorMessages;
 }
 public void setErrorMessages(List<String> errorMessages) {
  this.errorMessages = errorMessages;
 }
}

■workspace/BookLog/src/booklog/filter/RequestEncodingFilter.java
package booklog.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
/**
* Servlet Filter implementation class RequestEncodingFilter
*/
@WebFilter("/booklog/*")
public class RequestEncodingFilter implements Filter {
 /**
  * Default constructor.
  */
 public RequestEncodingFilter() {
  // BOOKLOG Auto-generated constructor stub
 }
 /**
  * @see Filter#destroy()
  */
 public void destroy() {
  // BOOKLOG Auto-generated method stub
 }
 /**
  * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
  */
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
  // BOOKLOG Auto-generated method stub
  // place your code here
  request.setCharacterEncoding("utf-8");
  // pass the request along the filter chain
  chain.doFilter(request, response);
 }
 /**
  * @see Filter#init(FilterConfig)
  */
 public void init(FilterConfig fConfig) throws ServletException {
  // BOOKLOG Auto-generated method stub
 }
}

■workspace/BookLog/src/booklog/web/DeleteServlet.java
package booklog.web;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import booklog.dao.BooklogDAO;
/**
* 削除処理を行う。
*/
@WebServlet( urlPatterns= {"/booklog/delete"})
public class DeleteServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;
 protected void doPost(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  // リクエストパラメータから選択したISBN13を取得する
  String paramId = request.getParameter("isbn13");
  try(BooklogDAO dao = new BooklogDAO()) {
   // Stringからintへ変換し、daoで処理を行う。対象の読書履歴を1件削除し、成功すると1を返す。
   int result = dao.delete(paramId);
  } catch (Exception e) {
   throw new ServletException(e);
  }
  setMessage(request, "ISBN13[ " + paramId + " ]の削除処理が完了しました。");
  // 画面を返す
  // 完了画面を表示する
  RequestDispatcher rd = request.getRequestDispatcher("/booklog/search");
  rd.forward(request, response);
 }
 /**
  * JSPで表示するメッセージを設定する。
  *
  * @param request
  * サーブレットリクエスト
  * @param message
  * メッセージ文字列
  */
 protected void setMessage(HttpServletRequest request, String message) {
  request.setAttribute("message", message);
 }
}

■workspace/BookLog/src/booklog/web/DetailServlet.java
package booklog.web;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import booklog.dao.BooklogDAO;
import booklog.entity.Booklog;
/**
* Servlet implementation class DetailServlet
*/
@WebServlet( urlPatterns= {"/booklog/detail"})
public class DetailServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;
 /**
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
  * response)
  */
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  // リクエストパラメータから選択したISBN13を取得する
  String paramId = request.getParameter("isbn13");
  // daoで処理を行う。更新対象の読書履歴を1件取得する。
  Booklog blog;
  try (BooklogDAO dao = new BooklogDAO()){
   // 取得結果を取得
   blog = dao.detail(paramId);
  } catch (Exception e) {
   throw new ServletException(e);
  }
  // 読書履歴1件のvoをリクエスト属性へバインド
  request.setAttribute("blog", blog);
  // 画面を返す
  // 詳細結果を表示する
  RequestDispatcher rd = request.getRequestDispatcher("/detail.jsp");
  rd.forward(request, response);
 }
 /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
  * response)
  */
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  // BOOKLOG Auto-generated method stub
  doGet(request, response);
 }
}

■workspace/BookLog/src/booklog/web/InputServlet.java
package booklog.web;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import booklog.entity.Booklog;
/**
* 新規登録の入力画面を表示する。
*/
@WebServlet( urlPatterns= {"/booklog/input"})
public class InputServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;
 /**
  * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse
  * response)
  */
 protected void doGet(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  // voの作成
  Booklog blog = new Booklog();
  // 新規登録であることを判別するためisbn13=nullとしている。
  blog.setIsbn13(null);
  // タスク1件のvoをリクエスト属性へバインド
  request.setAttribute("blog", blog);
  // 詳細画面を表示する
  RequestDispatcher rd = request.getRequestDispatcher("/detail.jsp");
  rd.forward(request, response);
 }
}

■workspace/BookLog/src/booklog/web/RegisterServlet.java
package booklog.web;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import booklog.dao.BooklogDAO;
import booklog.entity.Booklog;
/**
* 登録処理を行う。
*/
@WebServlet( urlPatterns= {"/booklog/register"})
public class RegisterServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;
 /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
  * response)
  */
 protected void doPost(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  // リクエストパラメータを受け取り、BLOGに格納する準備をする
  String isbn13 = request.getParameter("isbn13");
  String isbn10 = request.getParameter("isbn10");
  String bookname = request.getParameter("bookname");
  String author = request.getParameter("author");
  String publisher = request.getParameter("publisher");
  String genre = request.getParameter("genre");
  String inputIssuedate = request.getParameter("issuedate");
  String inputGetdate = request.getParameter("getdate");
  String inputReaddate = request.getParameter("readdate");
  int ownership = Integer.parseInt(request.getParameter("ownership"));
  int purchase = Integer.parseInt(request.getParameter("purchase"));
  String library = request.getParameter("library");
  String overview = request.getParameter("overview");
  String impressions = request.getParameter("impressions");
  int state = Integer.parseInt(request.getParameter("state"));
  String coverimg = request.getParameter("coverimg");
  String mode = request.getParameter("mode");
  Booklog blog = new Booklog();
  blog.setIsbn13(isbn13);
  blog.setIsbn10(isbn10);
  blog.setBookname(bookname);
  blog.setAuthor(author);
  blog.setPublisher(publisher);
  blog.setGenre(genre);
  blog.setInputIssuedate(inputIssuedate);
  blog.setInputGetdate(inputGetdate);
  blog.setInputReaddate(inputReaddate);
  blog.setOwnership(ownership);
  blog.setPurchase(purchase);
  blog.setLibrary(library);
  blog.setOverview(overview);
  blog.setImpressions(impressions);
  blog.setState(state);
  blog.setCoverimg(coverimg);
  // 入力チェックを行う。
  boolean checkResult = blog.valueCheck();
  // もし入力チェックエラーがあった場合は、エラーメッセージを表示し、再入力させるため元の詳細画面へ戻る
  if (! checkResult ) {
   request.setAttribute("errorMessages",blog.getErrorMessages());
   // 読書履歴1件のvoをリクエスト属性へバインド
   request.setAttribute("blog",blog);
   RequestDispatcher rd = request.getRequestDispatcher("/detail.jsp");
   rd.forward(request, response);
   return;
  }
  String message ="";
  try(BooklogDAO dao = new BooklogDAO()) {
   // 更新または、登録処理を行う
   // mode が"insert"のときは、新規登録、以外は更新
   if (mode.equals("insert")) {
    dao.registerInsert(blog);
    message ="ISBN13[" + isbn13 + "]の新規登録処理が完了しました。";
   } else {
    dao.registerUpdate(blog);
    message ="ISBN13[" + isbn13 + "]の更新処理が完了しました。";
   }
   setMessage(request, message);
  } catch (Exception e) {
   throw new ServletException(e);
  }
  // 画面を返す
  // 完了画面を表示する
  RequestDispatcher rd = request.getRequestDispatcher("/booklog/search");
  rd.forward(request, response);
 }
 /**
  * JSPで表示するメッセージを設定する。
  *
  * @param request
  * サーブレットリクエスト
  * @param message
  * メッセージ文字列
  */
 protected void setMessage(HttpServletRequest request, String message) {
  request.setAttribute("message", message);
 }
}

■workspace/BookLog/src/booklog/web/SearchServlet.java
package booklog.web;
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import booklog.dao.BooklogDAO;
import booklog.entity.Booklog;
/**
* 検索機能、読書履歴一覧を取得し、一覧結果へフォワードする
*/
@WebServlet( urlPatterns={"/booklog/search"})
public class SearchServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;
 /**
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
  * response)
  */
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  // DAOの取得
  try(BooklogDAO blog = new BooklogDAO()) {
   // 検索を行う
   List<Booklog> list = blog.booklogList();
   // 検索結果をリクエスト属性へ格納
   request.setAttribute("booklogList", list);
  } catch (Exception e) {
   throw new ServletException(e);
  }
  // 検索一覧を表示する
  RequestDispatcher rd = request.getRequestDispatcher("/search.jsp");
  rd.forward(request, response);
 }
 @Override
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  // BOOKLOG Auto-generated method stub
  doGet(request, response);
 }
}

■workspace/BookLog/WebContent/META-INF/context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context>
 <Resource driverClassName="org.mariadb.jdbc.Driver"
  initialSize="1"
  maxIdle="1"
  maxWaitMillis="-1"
  name="jdbc/localDB"
  type="javax.sql.DataSource"
  url="jdbc:mysql://127.0.0.1:3306/test"
  username="root"
  password="password"
  defaultAutoCommit="false"
 />
</Context>

■workspace/BookLog/WebContent/WEB-INF/web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
 <display-name>BookLog</display-name>
 <resource-ref>
  <res-ref-name>jdbc/localDB</res-ref-name>
  <res-type>javax.sql.DataSource</res-type>
  <res-auth>Container</res-auth>
 </resource-ref>
</web-app>

■workspace/BookLog/WebContent/detail.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-Control" content="no-cache">
<meta http-equiv="Expires" content="0">
<title>読書履歴詳細画面</title>
<jsp:include page="header.jsp" />
<script type="text/javascript">
window.onload = function() {
 var state = document.getElementById("state");
 state.selectedIndex = ${blog.state};
};
</script>
</head>
<body>
<jsp:include page="nav.jsp" />
<div class="container">
<form id="sender" action="register" method="POST">
<table class="table">
 <tr>
  <th align="right">ISBN13:</th>
  <td>
   <c:choose>
    <c:when test="${blog.isbn13 != null}">
     <c:out value="${blog.isbn13}" />
    </c:when>
    <c:otherwise>
     <input type="text" name="isbn13" value="<c:out value="${blog.isbn13}" />" size="14"/>
    </c:otherwise>
   </c:choose>
  </td>
  <th align="right">ISBN10:</th>
  <td><input type="text" name="isbn10" value="<c:out value="${blog.isbn10}" />" size="11"/></td>
  <th align="right">状 況:</th>
  <td>
   <select name="state" id="state">
    <option value="0">未読 </option>
    <option value="1">既読 </option>
    <option value="2">読書中</option>
   </select>
  </td>
  <td rowspan=10><c:if test="${blog.isbn13 != null}"><c:if test="${blog.coverimg != ''}"><img height="250" src="/BookLog/img/${blog.coverimg}"></c:if></c:if></td>
 </tr>
 <tr>
  <th align="right">書 名:</th>
  <td colspan=3><input type="text" name="bookname" value="<c:out value="${blog.bookname}" />" maxlength="50" size="45"/></td>
  <th align="right">分 類:</th>
  <td><input type="text" name="genre" value="<c:out value="${blog.genre}" />" maxlength="25" size="14"/></td>
 </tr>
 <tr>
  <th align="right">著 者:</th>
  <td colspan=3><input type="text" name="author" value="<c:out value="${blog.author}" />" maxlength="25" size="45"/></td>
  <th align="right">表 紙:</th>
  <td><input type="text" name="coverimg" value="<c:out value="${blog.coverimg}" />" maxlength="25" size="14"/></td>
 </tr>
 <tr>
  <th align="right">出版社:</th>
  <td colspan=3><input type="text" name="publisher" value="<c:out value="${blog.publisher}" />" maxlength="25" size="45"/></td>
  <th>価 格:</th>
  <td><input type="text" name="purchase" value="<c:out value="${blog.purchase}" />" maxlength="7" size="5"/></td>
 </tr>
 <tr>
  <th align="right">発行日:</th>
  <td>
  <c:choose>
   <c:when test="${blog.inputIssuedate != null }">
    <input type="text" name="issuedate" value="<c:out value="${blog.inputIssuedate}" />" size="10"/>
   </c:when>
   <c:otherwise>
    <input type="text" name="issuedate" value="<fmt:formatDate value="${blog.issuedate}" pattern="yyyy-MM-dd"/>" size="10"/>
   </c:otherwise>
  </c:choose>
  </td>
  <th align="right">入手日:</th>
  <td>
  <c:choose>
   <c:when test="${blog.inputGetdate != null }">
    <input type="text" name="getdate" value="<c:out value="${blog.inputGetdate}" />" size="10"/>
   </c:when>
   <c:otherwise>
    <input type="text" name="getdate" value="<fmt:formatDate value="${blog.getdate}" pattern="yyyy-MM-dd"/>" size="10"/>
   </c:otherwise>
以降、溢れたので(30,000字の制限)、続きはコメントに投稿します。

■workspace/BookLog/WebContent/header.jsp
溢れたので、コメントに投稿します。

■workspace/BookLog/WebContent/index.jsp
溢れたので、コメントに投稿します。

■workspace/BookLog/WebContent/nav.jsp
溢れたので、コメントに投稿します。

■workspace/BookLog/WebContent/search.jsp
溢れたので、コメントに投稿します。

コメント一覧

オーナー
デバッグ①
投稿の昨日の今日ではありますが、デバッグ投稿です。
すみません。
入力エリアの幅の修正をしていて、
・見出しのalign=rightが利かない(bootstrap配下では)
・「所有」が、設定値を反映しない→ついでにラジオボタンに変更
などのバグを見つけてしまい、以下に訂正しました。(バグは晒したまま、追加投稿する厚かましさ、すみません)

■workspace/BookLog/WebContent/detail.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-Control" content="no-cache">
<meta http-equiv="Expires" content="0">
<title>読書履歴詳細画面</title>
<jsp:include page="header.jsp" />
<script type="text/javascript">
window.onload = function() {
 var state = document.getElementById("state");
 state.selectedIndex = ${blog.state};
};
</script>
</head>
<body>
<jsp:include page="nav.jsp" />
<div class="container">
<form id="sender" action="register" method="POST">
<table class="table">
 <tr>
  <th><div class="float-right">ISBN13:</div></th>
  <td>
   <c:choose>
    <c:when test="${blog.isbn13 != null}">
     <c:out value="${blog.isbn13}" />
    </c:when>
    <c:otherwise>
     <input type="text" name="isbn13" value="<c:out value="${blog.isbn13}" />" size="14"/>
    </c:otherwise>
   </c:choose>
  </td>
  <th><div class="float-right">ISBN10:</div></th>
  <td><input type="text" name="isbn10" value="<c:out value="${blog.isbn10}" />" size="11"/></td>
  <th>状 況:</th>
  <td>
   <select name="state" id="state">
    <option value="0">未読 </option>
    <option value="1">既読 </option>
    <option value="2">読書中</option>
   </select>
  </td>
  <td rowspan=6><c:if test="${blog.isbn13 != null}"><c:if test="${blog.coverimg != ''}"><img height="300" src="/BookLog/img/${blog.coverimg}"></c:if></c:if></td>
 </tr>
 <tr>
  <th><div class="float-right">書 名:</div></th>
  <td colspan=3><input type="text" name="bookname" value="<c:out value="${blog.bookname}" />" maxlength="50" size="43"/></td>
  <th>分 類:</th>
  <td><input type="text" name="genre" value="<c:out value="${blog.genre}" />" maxlength="25" size="14"/></td>
 </tr>
 <tr>
  <th><div class="float-right">著 者:</div></th>
  <td colspan=3><input type="text" name="author" value="<c:out value="${blog.author}" />" maxlength="25" size="43"/></td>
  <th>表 紙:</th>
  <td><input type="text" name="coverimg" value="<c:out value="${blog.coverimg}" />" maxlength="25" size="14"/></td>
 </tr>
 <tr>
  <th><div class="float-right">出版社:</div></th>
  <td colspan=3><input type="text" name="publisher" value="<c:out value="${blog.publisher}" />" maxlength="25" size="43"/></td>
  <th>価 格:</th>
  <td><input type="text" name="purchase" value="<c:out value="${blog.purchase}" />" maxlength="7" size="5"/></td>
 </tr>
 <tr>
  <th><div class="float-right">発行日:</div></th>
  <td>
  <c:choose>
   <c:when test="${blog.inputIssuedate != null }">
    <input type="text" name="issuedate" value="<c:out value="${blog.inputIssuedate}" />" size="10"/>
   </c:when>
   <c:otherwise>
    <input type="text" name="issuedate" value="<fmt:formatDate value="${blog.issuedate}" pattern="yyyy-MM-dd"/>" size="10"/>
   </c:otherwise>
  </c:choose>
  </td>
  <th><div class="float-right">入手日:</div></th>
  <td>
  <c:choose>
   <c:when test="${blog.inputGetdate != null }">
    <input type="text" name="getdate" value="<c:out value="${blog.inputGetdate}" />" size="10"/>
   </c:when>
   <c:otherwise>
    <input type="text" name="getdate" value="<fmt:formatDate value="${blog.getdate}" pattern="yyyy-MM-dd"/>" size="10"/>
   </c:otherwise>
  </c:choose>
  </td>
  <th>読了日:</th>
  <td>
  <c:choose>
   <c:when test="${blog.inputReaddate != null }">
    <input type="text" name="readdate" value="<c:out value="${blog.inputReaddate}" />" size="10"/>
   </c:when>
   <c:otherwise>
    <input type="text" name="readdate" value="<fmt:formatDate value="${blog.readdate}" pattern="yyyy-MM-dd"/>" size="10"/>
   </c:otherwise>
  </c:choose>
  </td>
 </tr>
 <tr>
  <th>図書館・書店:</th>
  <td colspan=3><input type="text" name="library" value="<c:out value="${blog.library}" />" maxlength="25" size="43"/></td>
  <th>所 有:</th>
  <td>
   <input type="radio" name="ownership" <c:if test="${blog.ownership == '1'}">checked</c:if> value="1" /> Yes 
   <input type="radio" name="ownership" <c:if test="${blog.ownership == '0'}">checked</c:if> value="0" /> No
  </td>
 </tr>
  <tr>
  <th><div class="float-right">概略・副題:</div></th>
  <td colspan=6><input type="text" name="overview" value="<c:out value="${blog.overview}" />" maxlength="255" size="100"/></td>
 </tr>
  <tr>
  <th valign="top"><div class="float-right">感 想:</div></th>

~以下省略~
オーナー
search.jsp
■workspace/BookLog/WebContent/search.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<jsp:include page="header.jsp" />
<title>読書履歴一覧</title>
</head>
<body>
 <jsp:include page="nav.jsp" />
 <div class="container">
 <table class="table table-bordered">
  <tr>
   <th>ISBN13</th>
   <th>書名</th>
   <th>著者</th>
   <th>入手日</th>
   <th>状態</th>
  </tr>
  <c:forEach items="${booklogList}" var="blog">
   <tr>
    <td><a href="./detail?isbn13=<c:out value="${blog.isbn13}" />">
     <c:out value="${blog.isbn13}" /></a></td>
    <td><c:out value="${blog.bookname}" /></td>
    <td><c:out value="${blog.author}" /></td>
    <td><fmt:formatDate value="${blog.getdate }"
     pattern="yyyy-MM-dd" /></td>
    <td><c:choose>
     <c:when test="${blog.state == 0}">未読</c:when>
     <c:when test="${blog.state == 1}">既読</c:when>
     <c:otherwise>読書中</c:otherwise>
     </c:choose></td>
   </tr>
  </c:forEach>
 </table>
 </div>
</body>
</html>
オーナー
溢れた部分の追加投稿
溢れたので、続きをコメントで以下に、投稿します。
  </c:choose>
  </td>
  <th align="right">読了日:</th>
  <td>
  <c:choose>
   <c:when test="${blog.inputReaddate != null }">
    <input type="text" name="readdate" value="<c:out value="${blog.inputReaddate}" />" size="10"/>
   </c:when>
   <c:otherwise>
    <input type="text" name="readdate" value="<fmt:formatDate value="${blog.readdate}" pattern="yyyy-MM-dd"/>" size="10"/>
   </c:otherwise>
  </c:choose>
  </td>
 </tr>
 <tr>
  <th align="right">図書館・書店:</th>
  <td colspan=3><input type="text" name="library" value="<c:out value="${blog.library}" />" maxlength="25" size="45"/></td>
  <th align="right">所 有:</th>
  <td>
   <select name="ownership" id="ownership">
    <option value="0">貸出 </option>
    <option value="1">購入 </option>
   </select>
  </td>
 </tr>
  <tr>
  <th align="right">概略・副題:</th>
  <td colspan=5><input type="text" name="overview" value="<c:out value="${blog.overview}" />" maxlength="255" size="75"/></td>
 </tr>
  <tr>
  <th align="right" valign="top">感 想:</th>
  <td colspan=5><textarea name="impressions" cols="76" rows="5" style="font-family:HGゴシックM"><c:out value="${blog.impressions}" /></textarea></td>
 </tr>
</table>
<input type="hidden" name="isbn13" value="<c:out value="${ blog.isbn13 }" />" />
<input type="hidden" name="token" value="<c:out value="${ token }" />" />
<c:if test="${blog.isbn13 != null}">
 <input type="hidden" name="mode" value="update" />
 <input type="submit" class="btn btn-success" value="更新する" />
</c:if>
<c:if test="${blog.isbn13 == null}">
 <input type="hidden" name="mode" value="insert" />
 <input type="submit" class="btn btn-success" value="登録する" />
</c:if>
</form>
<c:if test="${blog.isbn13 != null}">
<br />
<form id="delete" action="delete" method="POST">
 <input type="hidden" name="isbn13" value="<c:out value="${ blog.isbn13 }" />" />
 <input type="hidden" name="token" value="<c:out value="${ token }" />" />
 <input type="submit" class="btn btn-warning" value="削除する" />
</form>
</c:if>
<br />
<div class="alert alert-danger" role="alert">
 <c:forEach items="${errorMessages}" var="errorMessage">
 ・${errorMessage }<br />
 </c:forEach>
</div>
</div>
</body>
</html>

■workspace/BookLog/WebContent/header.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" />
<style type="text/css">
body {
 padding-top: 20px;
}
</style>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>

■workspace/BookLog/WebContent/index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<jsp:include page="header.jsp" />
<title>読書履歴管理アプリケーション</title>
</head>
<body>
 <div class="container">
 <a href="./booklog/search" class="btn btn-success">読書履歴一覧の参照</a>
 </div>
</body>
</html>

■workspace/BookLog/WebContent/nav.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%
<nav class="navbar navbar-expand-lg navbar-light bg-light">
 <a class="navbar-brand" href="#">読書履歴管理</a>
 <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor03" aria-controls="navbarColor03" aria-expanded="false" aria-label="Toggle navigation">
  <span class="navbar-toggler-icon"></span>
 </button>
 <div class="collapse navbar-collapse" id="navbarColor03">
  <ul class="navbar-nav mr-auto">
   <li class="nav-item active">
    <a class="nav-link" href="./input">新規追加<span class="sr-only">(current)</span></a>
   </li>
   <li class="nav-item">
    <a class="nav-link" href="./search">一覧再表示</a>
   </li>
  </ul>
  <form class="form-inline my-2 my-lg-0" action="http://www.google.co.jp/search" method="get">
   <input class="form-control mr-sm-2" name="q" type="text" placeholder="Search">
   <button class="btn btn-secondary my-2 my-sm-0" type="submit">検索</button>
  </form>
 </div>
</nav>

■workspace/BookLog/WebContent/search.jsp
再度溢れたので、次のコメントへ
名前:
コメント:

※文字化け等の原因になりますので顔文字の投稿はお控えください。

コメント利用規約に同意の上コメント投稿を行ってください。

 

※ブログ作成者から承認されるまでコメントは反映されません。

  • Xでシェアする
  • Facebookでシェアする
  • はてなブックマークに追加する
  • LINEでシェアする

最新の画像もっと見る

最近の「Java」カテゴリーもっと見る

最近の記事
バックナンバー
人気記事