転職を繰り返したサラリーマンの多趣味ブログ

30才未経験でSEに転職した人の多趣味ブログ

【技術書メモ】基礎からのサーブレット㉕

検索機能のサンプル

public class ProductAction extends Action {

	@Override
	public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {

		HttpSession session = request.getSession();

		String keyword = request.getParameter("keyword");
		if(keyword == null) {
			keyword = "";
		}

		ProductDAO dao = new ProductDAO();
		List<Product> list = dao.search(keyword);

		session.setAttribute("list", list);

		return "product.jsp";

	}

}
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@include file="menu.jsp" %>

<p>検索キーワードを入力してください。</p>
<form action="Product.action" method="post">
	<input type="text" name="keyword">
	<input type="submit" value="検索">
</form>
<hr>

<table style="border-collapse:separate;border-spacing:10px;">
<c:forEach var="product" items="${list }">

	<tr>
		<td>商品${product.id }</td>
		<td><img src="image/${product.id }.jpg" height="64"></td>
		<td>${product.name }</td>
		<td>${product.price }円</td>
		<td><a href="CartAdd.action?id=${product.id }">カートに追加</a></td>
	</tr>

</c:forEach>
</table>

カート追加機能のサンプル

public class CartAddAction extends Action {

	@SuppressWarnings("unchecked")
	@Override
	public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {

		HttpSession session = request.getSession();

		// リクエストパラメータの取得(Productテーブルのid)
		int id = Integer.parseInt(request.getParameter("id"));

		// セッション属性からcartを取得
		List<Item> cart = (List<Item>)session.getAttribute("cart");
		// セッション属性からcartを取得できない場合
		if (cart == null) {
			// Itemクラスのリストを生成し、セッション属性に設定
			cart = new ArrayList<Item>();
			session.setAttribute("cart", cart);
		}

		// cartからProductクラスのidを取得し、リクエストパラメータから取得したidと一致した場合(画面からクリックされた商品とセッション属性内の商品を特定)
		for (Item i : cart) {
			if(i.getProduct().getId() == id) {
				// 個数を一つ増やす
				i.setCount(i.getCount() + 1);
				return "cart.jsp";
			}
		}

		// セッション属性からlistを取得(cartへ格納する処理)
		List<Product> list = (List<Product>)session.getAttribute("list");
		for (Product p : list) {
			// listのidと、リクエストパラメータから取得したidが一致した場合
			if(p.getId() == id) {
				// Itemクラスを作成し、cartに格納
				Item i = new Item();
				i.setProduct(p);
				i.setCount(1);
				cart.add(i);
			}
		}

		return "cart.jsp";
	}

}
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@include file="menu.jsp" %>

<c:choose>
	<c:when test = "${cart.size()>0 }">
		<p>${cart.size() }種類の商品があります。</p>
		<hr>
	</c:when>
	<c:otherwise>
		<p>カートに商品がありません。</p>
	</c:otherwise>
</c:choose>

<table style="border-collapse:separate;border-spacing:10px;">
<c:forEach var="item" items="${cart }">
	<tr>
	<td>商品${item.product.id }</td>
	<td><img src="image/${item.product.id }.jpg" height="96"></td>
	<td>${item.product.name }</td>
	<td>${item.product.price }円</td>
	<td>${item.count }個</td>
	<td><a href="CartRemove.action?id=${item.product.id }">カートから削除</a></td>
	</tr>
</c:forEach>
</table>

購入画面のサンプル

// 購入前の確認アクション
public class PreviewAction extends Action {

	@SuppressWarnings("unchecked")
	@Override
	public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {

		HttpSession session = request.getSession();

		// ログイン確認
		if(session.getAttribute("customer") == null) {

			return "preview-error-login.jsp";

		}

		// カートに品物が追加されているか確認
		List<Item> cart = (List<Item>)session.getAttribute("cart");
		if(cart == null || cart.size() == 0) {
			return "preview-error-cart.jsp";
		}

		return "purchase-in.jsp";

	}

}

購入情報の登録処理サンプル

public class PurchaseDAO extends DAO {

	public boolean insert (List<Item> cart, String name, String address) throws Exception {

		// Connectionオブジェクトの取得
		Connection con = getConnection();
		// 自動コミットの無効にし、コミット、ロールバックを手動で行えるようにする
		con.setAutoCommit(false);

		for (Item item : cart) {

			PreparedStatement ps = con.prepareStatement("insert into purchase values(null, ?, ?, ?, ?, ?, ?)");

			// SQLのプレースホルダの設定
			Product p = item.getProduct();
			ps.setInt(1, p.getId());
			ps.setString(2, p.getName());
			ps.setInt(3, p.getPrice());
			ps.setInt(4, item.getCount());
			ps.setString(5, name);
			ps.setString(6, address);

			// inset文の実行した行数を返却
			int line = ps.executeUpdate();

			ps.close();

			if(line != 1) {

				// ロールバックの実行
				con.rollback();
				con.setAutoCommit(true);
				con.close();

				return false;

			}
		}

		// コミットの実行
		con.commit();
		con.setAutoCommit(true);
		con.close();

		return true;

	}

}
public class PurchaseAction extends Action {

	@SuppressWarnings("unchecked")
	@Override
	public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {

		HttpSession session = request.getSession();

		String name = request.getParameter("name");
		String address = request.getParameter("address");
		if(name.isEmpty() || address.isEmpty()) {
			return "purchase-error-empty.jsp";
		}

		// 購入情報の登録
		PurchaseDAO dao = new PurchaseDAO();
		List<Item> cart = (List<Item>)session.getAttribute("cart");
		if(cart == null || !dao.insert(cart, name, address)) {
			return "purchase-error-insert.jsp";
		}

		// 購入済みのカートを削除
		session.removeAttribute("cart");
		// TODO 自動生成されたメソッド・スタブ
		return null;
	}

}