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

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

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

JavaBeans

JavaBeans・・・Javaプログラムをコンポーネントにするための技術。JavaBeansの仕様に基づき作成したオブジェクトを、Beanという。Beanには、データの設定、取得が可能。
シリアライズ・・・オブジェクトをファイルなどに保存できる形式に変換すること。シリアライズを可能にするには、Serializableインタフェースを実装する。
Beanのクラス例

public class Product implements Serializable {

	private int id;
	private String name;
	private int price;

	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getPrice() {
		return price;
	}
	public void setPrice(int price) {
		this.price = price;
	}
}

DAOとは

DAO・・・データベースを操作する処理をまとめたクラス。アプリケーション本体とデータベースの処理を分離する効果がある。

// DAOの共通処理
public class DAO {

	// 1度取得したデータソースは、何度も使いまわすためにstaticフィールドに格納
	static DataSource ds;

	public Connection getConnection() throws Exception {

		if (ds == null) {

			// JNDIを使用するために、InitialContextクラスのオブジェクト生成
			InitialContext ic = new InitialContext();

			// データソースの取得
			ds = (DataSource)ic.lookup("java:/comp/env/jdbc/book");

		}

		// Connectionオブジェクトの返却
		return ds.getConnection();

	}

}
// 共通処理を用いたDAOの作成例
public class ProductDAO extends DAO {

	public List<Product> search(String keyword) throws Exception {

		List<Product> list = new ArrayList<>();

		// Connectionオブジェクトの取得
		Connection con = getConnection();

		// SQL文の指定
		PreparedStatement ps = con.prepareStatement("select * from product where name like ?");
		ps.setString(1, "%" + keyword + "%");

		// SQL文の実行
		ResultSet rs = ps.executeQuery();

		// 結果の取得
		while (rs.next()) {

			Product p = new Product();
			p.setId(rs.getInt("id"));
			p.setName(rs.getString("name"));
			p.setPrice(rs.getInt("price"));
			list.add(p);
		}

		// DBからの切断
		con.close();
		ps.close();

                // ResultSetオブジェクトはDBから切断時に破棄されるため、リストに格納し返却
		return list;

	}

	public int insert(Product product) throws Exception {

		// Connectionオブジェクトの取得
		Connection con = getConnection();

		// SQL文の指定
		PreparedStatement ps = con.prepareStatement("insert into product values(null, ?, ?)");
		ps.setString(1, product.getName());
		ps.setInt(2, product.getPrice());

		// SQL文の実行
		int line = ps.executeUpdate();

		// DBからの切断
		con.close();
		ps.close();

		return line;

	}
}
// 共通DAOクラスを使ったサーブレットクラス例
@WebServlet(urlPatterns={"/chapter15/search"})
public class Search extends HttpServlet {

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		PrintWriter pw = resp.getWriter();
		Page.header(pw);

		try {

			// リクエストパラメータの取得
			String keyword = req.getParameter("keyword");

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

			for(Product p : list) {

				pw.println(p.getId());
				pw.println(":");
				pw.println(p.getName());
				pw.println(":");
				pw.println(p.getPrice());
				pw.println("<br>");

			}

		} catch (Exception e) {
			e.printStackTrace(pw);
		}

		Page.footer(pw);
	}

}
@WebServlet(urlPatterns={"/chapter15/insert"})
public class Insert extends HttpServlet {

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		PrintWriter pw = resp.getWriter();
		Page.header(pw);
		try {

			// リクエストパラメータの取得
			String name = req.getParameter("name");
			int price = Integer.parseInt(req.getParameter("price"));

			Product p = new Product();
			p.setName(name);
			p.setPrice(price);

			ProductDAO dao = new ProductDAO();
			int line = dao.insert(p);

			if(line > 0) {

				pw.println("追加に成功");

			}


		} catch(Exception e) {

			e.printStackTrace(pw);

		}
		Page.footer(pw);
	}

}