#05:投稿したメッセージの削除機能の実装
このチャプターでは、投稿したメッセージの削除機能を実装します。
【PostDeleteServlet】package jp.paiza.servlet;
import java.io.*;
import java.sql.*;
import javax.sql.*;
import jakarta.annotation.*;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import jp.paiza.bean.*;
import jp.paiza.model.*;
@WebServlet("/post-delete")
public class PostDeleteServlet extends HttpServlet {
@Resource(name = "jdbc/datasource")
private DataSource ds;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
try (Connection con = ds.getConnection()) {
RequestDispatcher d =
req.getRequestDispatcher("/WEB-INF/jsp/post-delete.jsp");
d.forward(req, res);
} catch (SQLException e) {
throw new ServletException(e);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
try (Connection con = ds.getConnection()) {
RequestDispatcher d =
req.getRequestDispatcher("/posts");
d.forward(req, res);
} catch (SQLException e) {
throw new ServletException(e);
}
}
}
【post-delete.jsp】<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="c" uri="jakarta.tags.core" %>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>投稿削除</title>
<link rel="stylesheet" href="css/style.css" type="text/css">
</head>
<body>
<jsp:include page="header.jsp" />
<div class="page-background">
<div class="form-container">
<form action="/learning/post-delete" method="post">
<div class="user-info"><c:out value="${account.userId}" /></div>
<textarea
id="post-content"
name="content"
rows="4"
placeholder="いまどうしてる?" disabled>${post.content}</textarea>
<div class="form-actions">
<button type="submit">削除する</button>
</div>
<input type="hidden" id="id" name="id" value="${post.id}" />
</form>
</div>
</div>
</body>
</html>
【PostModel.delete】 public void delete(PostBean post) throws SQLException {
String sql = "delete from posts where id = ? and account_id = ?";
try (PreparedStatement query = con.prepareStatement(sql)) {
}
}
【PostModel】package jp.paiza.model;
import java.util.*;
import java.time.*;
import jp.paiza.bean.*;
import java.sql.*;
import jp.paiza.bean.AccountBean;
public class PostModel {
private Connection con;
public PostModel(Connection con) {
this.con = con;
}
public List<PostBean> findAll() throws SQLException {
String sql = "select posts.id, posts.account_id, accounts.user_id, posts.content, posts.created_at, posts.updated_at from posts inner join accounts on posts.account_id = accounts.id order by posts.id desc";
ArrayList<PostBean> l = new ArrayList<>();
try (PreparedStatement query = con.prepareStatement(sql)) {
ResultSet rs = query.executeQuery();
while (rs.next()) {
PostBean post = new PostBean();
post.setId(rs.getInt("id"));
post.setAccountId(rs.getInt("account_id"));
post.setUserId(rs.getString("user_id"));
post.setContent(rs.getString("content"));
post.setCreatedAt(rs.getTimestamp("created_at"));
post.setUpdatedAt(rs.getTimestamp("updated_at"));
l.add(post);
}
}
return l;
}
public void insert(PostBean post) throws SQLException {
String sql = "insert into posts (account_id, content) VALUES (?, ?)";
try (PreparedStatement query = con.prepareStatement(sql)) {
query.setInt(1, post.getAccountId());
query.setString(2, post.getContent());
query.executeUpdate();
}
}
public PostBean find(PostBean post) throws SQLException {
String sql = "select posts.id, posts.account_id, accounts.user_id, posts.content, posts.created_at, posts.updated_at from posts inner join accounts on posts.account_id = accounts.id where posts.id = ? and account_id = ?";
try (PreparedStatement query = con.prepareStatement(sql)) {
query.setInt(1, post.getId());
query.setInt(2, post.getAccountId());
ResultSet rs = query.executeQuery();
if (rs.next()) {
PostBean p = new PostBean();
p.setId(rs.getInt("id"));
p.setAccountId(rs.getInt("account_id"));
p.setUserId(rs.getString("user_id"));
p.setContent(rs.getString("content"));
p.setCreatedAt(rs.getTimestamp("created_at"));
p.setUpdatedAt(rs.getTimestamp("updated_at"));
return p;
}
}
throw new SQLException("postが存在しない");
}
public void update(PostBean post) throws SQLException {
String sql = "update posts set content = ? where id = ? and account_id = ?";
try (PreparedStatement query = con.prepareStatement(sql)) {
query.setString(1, post.getContent());
query.setInt(2, post.getId());
query.setInt(3, post.getAccountId());
query.executeUpdate();
}
}
public void delete(PostBean post) throws SQLException {
String sql = "delete from posts where id = ? and account_id = ?";
try (PreparedStatement query = con.prepareStatement(sql)) {
query.setInt(1, post.getId());
query.setInt(2, post.getAccountId());
query.executeUpdate();
}
}
}
【PostDeleteServlet】package jp.paiza.servlet;
import java.io.*;
import java.sql.*;
import javax.sql.*;
import jakarta.annotation.*;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import jp.paiza.bean.*;
import jp.paiza.model.*;
@WebServlet("/post-delete")
public class PostDeleteServlet extends HttpServlet {
@Resource(name = "jdbc/datasource")
private DataSource ds;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
try (Connection con = ds.getConnection()) {
int id = Integer.parseInt(req.getParameter("id"));
AccountBean account = (AccountBean) req.getSession().getAttribute("account");
PostBean post = new PostBean();
post.setId(id);
post.setAccountId(account.getId());
PostModel m = new PostModel(con);
req.setAttribute("post", m.find(post));
RequestDispatcher d =
req.getRequestDispatcher("/WEB-INF/jsp/post-delete.jsp");
d.forward(req, res);
} catch (SQLException e) {
throw new ServletException(e);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
try (Connection con = ds.getConnection()) {
int id = Integer.parseInt(req.getParameter("id"));
AccountBean account = (AccountBean) req.getSession().getAttribute("account");
PostBean post = new PostBean();
post.setId(id);
post.setAccountId(account.getId());
PostModel m = new PostModel(con);
m.delete(post);
RequestDispatcher d =
req.getRequestDispatcher("/posts");
d.forward(req, res);
} catch (SQLException e) {
throw new ServletException(e);
}
}
}
新・Java入門編36: JDBCについて学習しよう > SQLの実行1(SELECT)
https://paiza.jp/works/java/new-primer/java-new-primer-36/108002
新・Java入門編36: JDBCについて学習しよう > ResultSet
https://paiza.jp/works/java/new-primer/java-new-primer-36/108003
新・Java入門編27: 例外について学習しよう
https://paiza.jp/works/java/new-primer/java-new-primer-27
新・SQL入門編8: DELETE文を理解しよう
https://paiza.jp/works/sql/new-primer/sql-new-primer-8
インタフェースConnection
https://docs.oracle.com/javase/jp/17/docs/api/java.sql/java/sql/Connection.html
インタフェースPreparedStatement
https://docs.oracle.com/javase/jp/17/docs/api/java.sql/java/sql/PreparedStatement.html
インタフェースResultSet
https://docs.oracle.com/javase/jp/17/docs/api/java.sql/java/sql/ResultSet.html
クラスSQLException
https://docs.oracle.com/javase/jp/17/docs/api/java.sql/java/sql/SQLException.html
Class HttpServlet
https://jakarta.ee/specifications/servlet/6.1/apidocs/jakarta.servlet/jakarta/servlet/http/httpservlet
Interface HttpServletRequest
https://jakarta.ee/specifications/servlet/6.1/apidocs/jakarta.servlet/jakarta/servlet/http/httpservletrequest
Interface HttpServletResponse
https://jakarta.ee/specifications/servlet/6.1/apidocs/jakarta.servlet/jakarta/servlet/http/httpservletresponse
Interface HttpSession
https://jakarta.ee/specifications/servlet/6.1/apidocs/jakarta.servlet/jakarta/servlet/http/httpsession