|
| |
 |
Struts編 |
 |
◆Strutsとは? |
| StrutsとはJakartaプロジェクトが開発しているオープンソースのソフトウエアで、JavaでWebアプリケーションを開発する際に利用されるフレームワークです。Strutsを用いることによってWebアプリケーションの開発にかかる工数を削減することができます。StrutsはWebアプリケーションで必要になる共通する機能が提供されているので開発者は必要な場所にコードを書くだけ、または設定ファイルやリソースファイルに必要な設定やメッセージを記述するだけでWebアプリケーションを開発することが可能になります。 |
| ◆フレームワークとは? |
| フレームワークとはアプリケーションを作成する際に使用する枠組みのことです。フレームワークを使用することによってプログラマは用意された枠組みに必要なコードのみを記述するだけでよく、開発が容易にできるメリットがあります。また、プログラム全体の標準化にも役立ちます。 |
| ◆ここでの環境 |
| OS |
Windows XP |
| J2SE SDK |
1.4.1_01 |
| Tomcat |
4.1.12 |
| Struts |
1.0.2 |
|
|
|
|
| Strutsのサンプルを動かしてみよう |
| まず、StrutsについているサンプルのWEBアプリケーションを動かしてみましょう。 |
| ◆Javaの実行環境の構築 |
| アプリケーション編を参考にJ2SE SDKをインストールしてJavaの実行環境を構築します。 |
| ◆Tomcatを使用可能にする |
| Servlet編を参考にしてTomcatを使用可能にしてください。Tomcatがインストールされたフォルダのことを以後、Tomcatのフォルダとしたいと思います。 |
| ◆Strutsをダウンロードする |
StrutsはJakartaプロジェクトから提供されています。
Strutsのダウンロード → http://jakarta.apache.org/struts/
ここではjakarta-struts-1.0.2.zipをダウンロードしました。ダウンロードしたらそのファイルを解凍しましょう。解凍方法はこちらを参考にしてください。→ ダウンロードしたファイルを解凍するには |
| ◆StrutsのwarファイルをTomcatのwebappsフォルダにコピーする |
解凍してできたjakarta-struts-1.0.2のフォルダの中のwebappsフォルダの中に入っているwarファイルをTomcatのフォルダ\webappsにコピーします。
<コピーするファイル>
struts-blank.war
struts-documentation.war
struts-example.war
struts-exercise-taglib.war
struts-template.war
struts-upload.war |
| ◆Tomcatの起動 |
| Tomcatを起動します。Tomcatのフォルダ\binのフォルダに入っている「startup.bat」ファイルを実行することで起動できます。起動すると上でコピーしたファイルが解凍されていると思います。Tomcatのフォルダ\webappsの中を見てみてください。おおお、フォルダができてるぞ! |
| ◆ブラウザでサンプル画面を見てみよう |
ブラウザを起動して以下のURLを指定します。 http://localhost:8080/struts-example/
おおお!サンプル画面が見れましたね!リンク先にページに行ってデータを登録したりしてみてください。
|
| |
| Strutsを使って自分のWEBアプリケーションの作成 |
| ここでは、名前、メールアドレス、メッセージを送信して表示するだけの簡単なWEBアプリケーションを作りたいと思います。 |
| 1.Strutsを利用するための雛形の用意 |
| Tomcatのフォルダ\webappsの下にある「struts-blank.war」ファイルを同じ場所に名前を変えてコピーします。ここでは「javahello.war」という名前でコピーしました。コピーしたらTomcatを再起動しましょう。javahelloというフォルダができたと思います。ここにはStrutsを利用するために必要なファイルが入っています。 |
 |
■Strutsを利用する上で必要になるファイルの説明
| WEB-INF\*.tld |
Strutsのタグライブラリディスクリプタ。 |
| WEB-INF\classes\ApplicationResources.properties |
アプリケーションで使用するメッセージリソースファイル。 |
| WEB-INF\struts-confg.xml |
Strutsの設定ファイル。 |
| WEB-INF\web.xml |
WEBアプリケーションの設定ファイル。 |
|
| ■ここで作成するファイル一覧 |
| sendMessage.jsp |
名前、メールアドレス、メッセージを入力して送信するページ。 |
| showMessage.jsp |
送られてきたデータを表示するページ。 |
| SendMessageForm.java |
アクションフォームBean。sendMessage.jspファイルの中のフォームに対応するクラスです。validateメソッドに入力値のチェックを記述します。 |
| SendMessageAction.java |
アクションクラス。sendMessage.jspファイルからのデータ送信の動作に対応するクラスです。performメソッドにビジネスロジックを記述します。 |
|
| |
| 2.sendMessage.jspファイルの作成 |
| [Tomcatのフォルダ]\webapps\javahello\sendMessage.jspファイルを作成します。以下が作成したファイルです。雛形に入っているindex.jspをコピーして作ると簡単です。赤い文字のところが修正した場所です。 |
| sendMessage.jsp(ここからダウンロード) |
<%@ page contentType="text/html; charset=Shift_JIS" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<html:html locale="true">
<head>
<title><bean:message key="sendMessage.title"/></title>
<html:base/>
</head>
<body bgcolor="white">
<logic:notPresent name="org.apache.struts.action.MESSAGE" scope="application">
<font color="red">
ERROR: Application resources not loaded -- check servlet container
logs for error messages.
</font>
</logic:notPresent>
<h3><bean:message key="sendMessage.heading"/></h3>
<p><bean:message key="sendMessage.message"/></p>
<html:errors/>
<html:form action="/sendMessage" focus="name">
<bean:message key="sendMessage.form.name"/>
<html:text property="name" size="20" maxlength="50"/>
<br>
<bean:message key="sendMessage.form.email"/>
<html:text property="email" size="20" maxlength="50"/>
<br>
<bean:message key="sendMessage.form.message"/>
<br>
<html:textarea property="message" cols="50" rows="5"/>
<br>
<html:submit property="submit" value="送信"/>
</html:form>
</body>
</html:html> |
|
|
| |
| 3.showMessage.jspファイルの作成 |
| [Tomcatのフォルダ]\webapps\javahello\showMessage.jspファイルを作成します。送られてきたデータを表示するページです。 |
| showMessage.jsp(ここからダウンロード) |
<%@ page contentType="text/html; charset=Shift_JIS" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<html:html locale="true">
<head>
<title><bean:message key="showMessage.title"/></title>
<html:base/>
</head>
<body bgcolor="white">
<h3><bean:message key="showMessage.heading"/></h3>
<bean:message key="sendMessage.form.name"/>:
<bean:write name="sendMessageForm" property="name" scope="request"/><br>
<bean:message key="sendMessage.form.email"/>:
<bean:write name="sendMessageForm" property="email" scope="request"/><br>
<bean:message key="sendMessage.form.message"/>:
<pre><bean:write name="sendMessageForm" property="message" scope="request"/></pre><br>
</body>
</html:html>
|
|
|
| |
| 4.SendMessageForm.javaの作成 |
| [Tomcatのフォルダ]\webapps\javahello\WEB-INF\classes\javahello\SendMessageForm.javaを作成します。classesの下にjavahelloというディレクトリを作ってください。 |
| SendMessageForm.java(ここからダウンロード) |
package javahello;
import javax.servlet.http.*;
import org.apache.struts.action.*;
/**
* アクションフォームBeanクラス
* ActionFormを継承します
*/
public final class SendMessageForm extends ActionForm {
private String name;
private String email;
private String message;
public void setName(String name) {
this.name = toSJIS(name);
}
public String getName() {
return name;
}
public void setEmail(String email) {
this.email = toSJIS(email);
}
public String getEmail() {
return email;
}
public void setMessage(String message) {
this.message = toSJIS(message);
}
public String getMessage() {
return message;
}
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
// エラーを格納するActionErrorsオブジェクトを作成
ActionErrors errors = new ActionErrors();
// 入力チェック
if (name == null || name.equals("")) {
// ActionErrorオブジェクトを作成して格納
// ActionErrorオブジェクトのコンストラクタの第1引数は
// リソースファイルに記述してあるキーを渡す
errors.add("name" , new ActionError("error.name.required"));
}
if (email == null || email.equals("")) {
errors.add("email", new ActionError("error.email.required"));
}
if (message == null || message.equals("")) {
errors.add("message" , new ActionError("error.message.required"));
}
return errors;
}
/**
* iso-8859-1からShift_JISへの文字コード変換メソッド
*/
private String toSJIS(String str) {
try {
str = new String(str.getBytes("iso-8859-1"), "Shift_JIS");
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
} |
|
|
| |
| 4.SendMessageAction.javaの作成 |
| [Tomcatのフォルダ]\webapps\javahello\WEB-INF\classes\javahello\SendMessageAction.javaを作成します。 |
| SendMessageAction.java(ここからダウンロード) |
package javahello;
import javax.servlet.http.*;
import org.apache.struts.action.*;
/**
* アクションクラス
* Actionを継承します
*/
public final class SendMessageAction extends Action {
public ActionForward perform(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) {
// フォームBeanを取得します
SendMessageForm sendMessageForm = (SendMessageForm)form;
// 値を取得
String name = sendMessageForm.getName();
String email = sendMessageForm.getEmail();
String message = sendMessageForm.getMessage();
/*** ここにビジネスロジックを記述 ***/
// "success"という名前で登録されている転送先を検索して返却
// (struts-config.xmlファイルに記述されている)
return (mapping.findForward("success"));
}
} |
|
| ※Struts1.1からperformメソッドではなくExceptionをスローできるexecuteメソッドを使用することが推奨されています。performメソッドをexecuteメソッドに変更することで対応できます。 |
|
|
|
| |
| 5.コンパイル |
| コンパイルするにはサーブレット編ででてきたservlet.jarと、上でダウンロードして解凍したjakarta-struts-1.0.2のlibというフォルダに入っているstruts.jarファイルをCLASSPATHに追加しなければなりません。CLASSPATHへの追加方法はアプリケーション編を参考にしてください。 |
| コマンドプロンプト |
| C:\>cd C:\Program
Files\Apache Group\Tomcat 4.1\webapps\javahello\WEB-INF\classes\javahello
C:\Program Files\Apache Group\Tomcat 4.1\webapps\javahello\WEB-INF\classes\javahello>javac
*.java
C:\Program Files\Apache Group\Tomcat 4.1\webapps\javahello\WEB-INF\classes\javahello>
|
|
| |
| 6.Strutsの設定ファイル(struts-config.xml)の編集 |
| [Tomcatのフォルダ]\webapps\javahello\WEB-INF\struts-config.xmlファイルを編集します。以下のように編集してください。赤字の部分が追加された場所です。 |
| struts-confg.xml |
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.0//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_0.dtd">
<!--
This is a blank Struts configuration file based on the example application,
with commented examples of some items.
NOTE: If you have a generator tool to create the corresponding Java classes
for you, you could include the details in the "form-bean" declarations.
Otherwise, you would only define the "form-bean" element itself, with the
corresponding "name" and "type" attributes, as shown here.
-->
<struts-config>
<!-- ========== Data Source Configuration =============================== -->
<!--
<data-sources>
<data-source
autoCommit="false"
description="Example Data Source Configuration"
driverClass="org.postgresql.Driver"
maxCount="4"
minCount="2"
password="mypassword"
url="jdbc:postgresql://localhost/mydatabase"
user="myusername"
/>
</data-sources>
-->
<!-- ========== Form Bean Definitions =================================== -->
<form-beans>
<form-bean name="sendMessageForm"
type="javahello.SendMessageForm"/>
<!-- Example logon form bean
<form-bean name="logonForm"
type="org.apache.struts.example.LogonForm"/>
-->
</form-beans>
<!-- ========== Global Forward Definitions ============================== -->
<global-forwards>
<!-- Example logon forward
<forward name="logon" path="/logon.jsp"/>
-->
</global-forwards>
<!-- ========== Action Mapping Definitions ============================== -->
<action-mappings>
<action path="/sendMessage"
type="javahello.SendMessageAction"
name="sendMessageForm"
scope="request"
input="/sendMessage.jsp"
validate="true">
<forward name="success" path="/showMessage.jsp"/>
</action>
<!-- Example logon action
<action path="/logon"
type="org.apache.struts.example.LogonAction"
name="logonForm"
scope="request"
input="/logon.jsp">
</action>
-->
<!-- Example logoff action
<action path="/logoff"
type="org.apache.struts.example.LogoffAction">
<forward name="success" path="/index.jsp"/>
</action>
-->
<!-- The standard administrative actions available with Struts -->
<!-- These would be either omitted or protected by security -->
<!-- in a real application deployment -->
<action path="/admin/addFormBean"
type="org.apache.struts.actions.AddFormBeanAction"/>
<action path="/admin/addForward"
type="org.apache.struts.actions.AddForwardAction"/>
<action path="/admin/addMapping"
type="org.apache.struts.actions.AddMappingAction"/>
<action path="/admin/reload"
type="org.apache.struts.actions.ReloadAction"/>
<action path="/admin/removeFormBean"
type="org.apache.struts.actions.RemoveFormBeanAction"/>
<action path="/admin/removeForward"
type="org.apache.struts.actions.RemoveForwardAction"/>
<action path="/admin/removeMapping"
type="org.apache.struts.actions.RemoveMappingAction"/>
</action-mappings>
</struts-config>
|
|
|
| |
| 7.メッセージリソースファイル(ApplicationResources.properties)の編集 |
| [Tomcatのフォルダ]\webapps\javahello\WEB-INF\classes\ApplicationResources.propertiesファイルを編集します。 |
| ApplicationResources.properties(ここからダウンロード) |
sendMessage.title=StrutsでHello World
sendMessage.heading=メッセージの送信
sendMessage.message=お名前、メールアドレス、メッセージを入力して送信ボタンを押してください。
sendMessage.form.name=お名前
sendMessage.form.email=メールアドレス
sendMessage.form.message=メッセージ
showMessage.title=送信されたメッセージ
showMessage.heading=送信されたメッセージ
errors.header=<h4>エラーがあります</h4><ul>
errors.footer=</ul><hr>
error.name.required=<li>お名前を入力してください。</li>
error.email.required=<li>メールアドレスを入力してください。</li>
error.message.required=<li>メッセージを入力してください。</li> |
|
| (注意)Javaのリソースファイルは日本語を使用する場合ASCIIファイルに変換しなければなりません。国際化編を参考にして変換してください。 |
| |
| 8.Tomcatの再起動とWEBアプリケーションの実行 |
これですべてのファイルが揃いましたのでTomcatを再起動して設定を反映させてからブラウザで見てみましょう。以下のURLを指定してみてください。
http://localhost:8080/javahello/sendMessage.jsp
おおおおお! |
 |
| 何も入力しないで送信ボタンを押してみましょう。おおお!エラーが表示されましたね。これはSendMessageFormクラスのvalidateメソッドでチェックされて検出されたエラーですね。 |
 |
| 今度はすべての値を入力して送信してみましょう。 |
 |
| おおおお!メッセージが表示されましたね! |
| |
■書籍 Java関連の書籍 |
|
| |
|
| |
| ツールの部屋
- Java関連の書籍 - デザインパターン - 情報交換掲示板
- HOME |