画面で入力されたデータをテーブルに挿入する
JSPで表示された画面に値を入力します。
その値をサーブレットで受け取って、以下のテーブルにデータを挿入します。
create table member (id int auto_increment primary key, name varchar(10), age varchar(3));
まず、web.xmlです。
<?xml version="1.0" encoding="ISO-8859-1"?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4"> <servlet> <servlet-name>list</servlet-name> <servlet-class>controller.ListServlet</servlet-class> </servlet> <servlet> <servlet-name>create</servlet-name> <servlet-class>controller.CreateServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>list</servlet-name> <url-pattern>/member/list</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>create</servlet-name> <url-pattern>/member/create</url-pattern> </servlet-mapping> <resource-ref> <res-ref-name>jdbc/test</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref> </web-app>
今回使うのは、servlet-nameがcreateのものです。
CreateServlet.java
package controller; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import javax.annotation.Resource; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.sql.DataSource; public class CreateServlet extends HttpServlet { @Resource(name = "jdbc/test") private DataSource ds; public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { System.out.println("get request"); getServletContext().getRequestDispatcher("/WEB-INF/jsp/create.jsp").forward(req, res); } public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { System.out.println("post request"); Connection con = null; String name = req.getParameter("name"); String age = req.getParameter("age"); try { con = ds.getConnection(); String sql = "INSERT INTO member (name, age) VALUES(?,?)"; PreparedStatement stmt = con.prepareStatement(sql); stmt.setString(1, name); stmt.setString(2, age); stmt.executeUpdate(); res.sendRedirect(getServletContext().getContextPath() + "/member/list"); stmt.close(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (con != null) { con.close(); } } catch (SQLException e) { throw new ServletException(); } } } }
GETリクエストを、create.jspにフォワードしています。
create.jsp
<%@ page contentType="text/html; charset=utf-8" %> <%@ page session="false" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>new</title> </head> <form action="create" method="post"> <p> <b>name</b><br/> <input id="name" name="name" size="30" type="text" /> </p> <p> <b>age</b> <input id="age" name="age" size="10" type="text"/> </p> <p> <input id="submit" name="submit" type="submit" value="作成" /> </p> </form> </html>
これをCreateServletのdoPostで受け取って、データを挿入します。
最後、list.jspにリダイレクトします。
list.jsp
<%@ page contentType="text/html; charset=utf-8" %> <%@ page session="false" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head>list</head> <body> <table> <tr> <th>id</th> <th>name</th> <th>age</th> </tr> <c:forEach var="member" items="${members}"> <tr> <td>${member.id }</td> <td>${member.name}</td> <td>${member.age }</td> </tr> </c:forEach> </table> <br/> </body> </html>
実際にテーブルを見てもこんな風に挿入できています。
mysql> select * from member; +----+------+------+ | id | name | age | +----+------+------+ | 1 | sato | 27 | +----+------+------+ 1 row in set (0.00 sec)
build.xml
<?xml version="1.0" encoding="UTF-8" ?> <project basedir="." default="build"> <property name="name" value="love-report"/> <property name="base.dir" value="."/> <property name="appserver.dir" value="C:\Program Files\eclipse\pleiades\tomcat\6"/> <property name="deploy.dir" value="${appserver.dir}/webapps"/> <property name="src.dir" value="${base.dir}/WEB-INF/src"/> <property name="build.dir" value="${base.dir}/WEB-INF/classes"/> <path id="master-classpath"> <fileset dir="${base.dir}/WEB-INF/lib"> <include name="*.jar"/> </fileset> <fileset dir="${appserver.dir}/lib"> <include name="*.jar"/> </fileset> <pathelement path="${build.dir}"/> </path> <target name="build" description="Complie main source tree java files"> <mkdir dir="${build.dir}"/> <javac destdir="${build.dir}" debug="true" failonerror="true"> <src path="${src.dir}"/> <classpath refid="master-classpath"/> </javac> </target> <target name="deploy" depends="build" description="Deploy Application"> <copy todir="${deploy.dir}/${name}" preservelastmodified="true"> <fileset dir="${base.dir}"> <include name="**/*.*"/> </fileset> </copy> </target> <target name="clean"> <delete failonerror="false"> <fileset dir="${build.dir}"> <include name="**.*.class"/> <include name="**.*.properties"/> </fileset> </delete> </target> </project>