「第1回:Are you ready for Server Java ?」でも述べたように、サーバサイドアプリケーションの魅力は、与えられたコンテンツを参照するだけではなく、エンドユーザが自らコンテンツを累積していくことができる点にあります。ここでは、データベースへの登録について説明していきます。dbInput.jsp(リスト2)から入力された情報をdbInsert.jsp(リスト3)でデータベースにインサートします(図3)。
リスト2:dbInput.jsp
<%@ page contentType="text/html;charset=Windows-31J" %>
<html>
<head>
<title>データベース登録</title>
</head>
<body>
<form method="POST" action="dbInsert.jsp">
<table border="0">
<tr>
<th align="right">名前:</th>
<td><input type="text" name="name" size="15" maxlength="30" /></td>
</tr>
<tr>
<th align="right">出身国:</th>
<td><input type="text" name="country" size="15" maxlength="30" /></td>
</tr>
<tr>
<th align="right">享年:</th>
<td><input type="text" name="old" size="5" maxlength="3" />歳</td>
</tr>
<tr>
<th align="right">誕生日:</th>
<td><input type="text" name="birth" size="15" maxlength="10" /></td>
</tr>
<tr>
<th align="right">代表作:</th>
<td><input type="text" name="work" size="20" maxlength="50" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="登録" /></td>
</tr>
</table>
</form>
</body>
</html>
リスト3:dbInsert.jsp
<%@ page contentType="text/html;charset=Windows-31J" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
<fmt:requestEncoding value="Windows-31J" />
<sql:setDataSource var="db" dataSource="jdbc/Marugoto" />
<sql:update dataSource="${db}"> (1)
INSERT INTO artist(name,country,old,birth,work) VALUE(?,?,?,?,?)
<sql:param value="${param['name']}" />
<sql:param value="${param['country']}" />
<sql:param value="${param['old']}" />
<sql:param value="${param['birth']}" />
<sql:param value="${param['work']}" />
</sql:update>
<c:redirect url="dbInput.jsp" />

図3:HTMLフォームからの入力情報をデータベースに登録
|