フォームを Velocity で書き変える

CustomerSearch も Velocity で書き変えてみましょう。

ライブラリの追加、velocity-toolbox.xml の作成、velocity.properties の作成、web.xml の修正は前回と同様。

search.vm の作成

search.jsp を手直しして search.vm を作ります。

<!doctype html>
<html>
<head>
  <title>顧客マスタ参照</title>
  <link rel="stylesheet" href="search.css" type="text/css">
</head>
<body>
  <h1>顧客マスタ参照</h1>
  <form action="$link.setAction('/search')" method="post">
    <table>
      <tr>
        <td>顧客ID</td>
        <td><input type="text" name="id" size="5" required value="$!searchform.id"></td>
      </tr>
      <tr>
        <td>顧客名</td>
        <td><input type="text" name="name" size="20" readonly value="$!searchform.name"></td>
      </tr>
      <tr>
        <td>連絡先</td>
        <td><input type="text" name="phone" size="20" readonly value="$!searchform.phone"></td>
      </tr>
    </table>
    <p><input type="submit" value="検索"></p>
  </form>
</body>
</html>

$link は velocity-toolbox.xml で設定した StrutsLinkTool です。struts-config.xml に記述した action の path を指定します。また $!searchform.id 等は FormTool です。struts-config.xml を参照して対応する form の名前に紐づいている form-bean を参照します。! は沈黙参照と言って、中身が空のときには何も表示しないために付けます。

見てお分かりの通り、HTML5 で新たに追加された required 属性が使われています。Struts の html:text にはこれに対応する属性がない*1ので、ここにも Velocity を導入する利点があります。

index.jsp(ダミーページ)の修正

<!doctype html>
<html>
<head>
    <title>Index Page</title>
</head>
<body>
    <% response.sendRedirect("search.vm"); %>
</body>
</html>

リダイレクト先の修正。

struts-config.xml の修正

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd">

<struts-config>

  <form-beans>
    <form-bean name="searchform" type="jp.mydns.akanekodou.SearchActionForm" />
  </form-beans>

  <action-mappings>
    <action path="/search" name="searchform" type="jp.mydns.akanekodou.SearchAction" input="/search.vm" />
  </action-mappings>

</struts-config>

getInputForward 用の設定の修正。

*1:Validator を使えばチェックはできるのですが、HTML5 の required 属性のような動作をするわけではありません。