はじめのアプリ

tomcat6をインストールして、超簡単なstruts2のアプリを作成してみました。行った環境はMac OS10.5.5(Leopard)です。

tomcatのインストール

http://tomcat.apache.org/download-60.cgi」よりTomcat6.0.18のバイナリをダウンロードして、解凍します。解凍したものを適当な場所にコピーします。今回は、「/Library」以下に配置しました。

#cp -R apache-tomcat-6.0.18 /Library/Tomcat-6.1.18

それから「Tomcat manager」などが使えるようにするためユーザの設定を行います。conf/tomcat-users.xmlを以下のように変更、 managerとroleの権限をもつadminとユーザを作成しました。

<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="manager" />
<role rolename="admin" />
<user username="admin" password="*******" 
    roles="manager,admin" />
</tomcat-users>

この後、Tomcatを起動します。

#cd /Library/Tomcat-6.0.18
#./bin/startup.sh 

これで、ブラウザで「http://localhost:8080/」にアクセス、それで表示されるリンクから「Tomcat manager」や「Examples」を開いてみて動作を確認しました。

strutsを取得

http://struts.apache.org/download.cgi」より最新のStruts 2.0.11.2(struts-2.0.11.2-all.zip)を
ダウンロードして、解凍します。

strutsのアプリケーション作成

ディレクトリの作成、ライブラリのコピー
#mkdir struts-test
#ln -s /Users/nyaago/workspace/struts-test /Library/Tomcat-6.0.18/test
#cd struts-test

#mkdir WEB-INF
#mkdir WEB-INF/src
#mkdir < srcのサブディレクトリ> ...
#mkdir WEB-INF
#mkdir WEB-INF/src
#mkdir WEB-INF/lib
struts関連のjarファイル

解凍したstrutsディストリビューションのlibに含まれるファイル中、以下のものを作成したWEB-INF/libに配置しました。
commons-logging-1.0.4.jar
ognl-2.6.11.jar
xwork-2.0.5.jar
freemarker-2.3.8.jar
struts2-core-2.0.11.2.jar

web.xml

サンプルとしてついているblankアプリケーションの定義をもとに、WEB-INF/web.xmlを作成しました。

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" 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">

    <display-name>Struts Test</display-name>

    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>

</web-app>
antのbuild.xmlを作成

ここの例を参照にant用のbuild.xmlを作成しました。アプリケーションのルートパスに作成します。これを使ってアプリケーションのコンパイルやファイルコピー、アーカイブなどを行うようにします。

<project name="Struts 2 Tutorial" basedir="./WEB-INF" default="project">
    <!-- Project settings -->
    <property name="project.title" value="Struts 2 test"/>
	<property name="project.jar.file" value="struts-test.jar"/>
	  <path id="class.path">
		<fileset dir="lib">
		  <include name="**/*.jar"/>
		</fileset>
	  </path>

		<!-- Classpath for Project -->
		<path id="compile.classpath">
			<pathelement path ="lib/commons-beanutils.jar"/>
			<pathelement path ="lib/commons-digester.jar"/>
			<pathelement path ="lib/struts.jar"/>
			<pathelement path ="classes"/>
			<pathelement path ="${classpath}"/>
		</path>

		<!-- Check timestamp on files -->
		<target name="prepare">
			<tstamp/>
			<copy
				file="src/struts.xml"
				todir="classes"/>
		</target>
		<!-- Copy any resource or configuration files -->
		<target name="resources"> 
			<copy todir="classes" includeEmptyDirs="no">
				<fileset dir="src">
				<patternset>
					<include name="**/*.conf"/>
					<include name="**/*.properties"/>
					<include name="**/*.xml"/>
				</patternset>
				</fileset>
			</copy>
		</target>

		<!-- Normal build of application -->
		<target name="compile" depends="prepare,resources">
			<javac srcdir="src" destdir="classes" 
                         debug="true" debuglevel="lines,vars,source">
				<classpath refid="class.path"/>
			</javac>
			<jar
			jarfile="lib/${project.jar.file}"
  		       basedir="classes">
			<exclude name="**/*.xml"/>
            </jar>
		</target>
		<!-- Remove classes directory for clean build -->
		<target name="clean"
		  description="Prepare for clean build">
		  <delete dir="classes"/>
	      <mkdir  dir="classes"/>
		</target>

		<!-- Build entire project -->
		<target name="project" depends="clean,prepare,compile"/>

		<!-- Create binary distribution -->
		<target name="dist"
			description="Create binary distribution">
		  <mkdir
			dir="${distpath.project}"/>
		  <jar
			jarfile="${distpath.project}/${project.distname}.jar"
			basedir="./classes"/>
		  <copy
			file="${distpath.project}/${project.distname}.jar"
			todir="${distpath.project}"/>
		  <war
			basedir="../"
			warfile="${distpath.project}/${project.distname}.war"
			webxml="web.xml">
			<exclude name="${distpath.project}/${project.distname}.war"/>
		   </war>
    </target>


    <!-- Build project and create distribution-->
	<target name="all" depends="project"/>

 </project>

アプリケーションの実装

messageというキーのリクエストパラメータだけを返すようなアプリケーションを作成してみる。

struts.xml

srcディレクトリ直下にstruts.xmlを作成。パッケージ名hello,アクション名helloとしてアクションを定義します。

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

<struts>

    <constant name="struts.enable.DynamicMethodInvocation" value="true" />
    <constant name="struts.devMode" value="true" />

    <package name="hello" namespace="/hello" extends="struts-default">
        <action name="Hello!*" class="jp.nyaago.Hello" method="{1}" >
            <result name="msg">hello-msg.jsp</result>
        </action>
    </package>
</struts>
    1. actionタグのclass属性はアクションクラス名、method属性は、アクションメソッド名です。nameで使用されている「*」のところは、任意の値が入り、methodの{1}のところは、その値で置換されることになります。
    2. ここでの定義に対してリクエストのためにurlは「/.action<以下パラメータ>」というかたちになります。今回の場合の「*」の部分はアクションのメソッド名で置換されるかたちとなります。
    3. resultタグで表示するviewを指定します。resultタグのname属性の値はActionメソッドの結果値に対応します。
アクションクラス

属性としてmessageを含むクラスを定義。アクションメソッド(hello)では、何もせず、"msg"を返します。返された値に対応した(struts.xmlのresultタグのnameが"msg"のもの)Viewが表示されます。

package jp.nyaago;

/**
 * <code>Set welcome message.</code>
 */
public class Hello  {

    public String msg() throws Exception {
        return "msg";
    }

    /**
     * Field for Message property.
     */
    private String message = null;

    /**
     * Return Message property.
     *
     * @return Message property
     */
    public String getMessage() {
        if (message == null)
            return "empty";
        return message;
    }

    /**
     * Set Message property.
     *
     * @param message Text.
     */
    public void setMessage(String message) {
        this.message = message;
    }
}
View

struts.xmlのpackageタグのnamespaceの位置にresultタグで指定した名称(今回はアプリケーションルート下のhello/hello-msg.jsp)で表示jspを作成します。アクションで設定されたmessage属性を表示するだけのものです。

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
    <title><s:text name="Hello.message"/></title>
</head>

<body>
<h2>Message:<s:property value="message"/></h2>

</body>
</html>

コンパイル、確認

コンパイル

アプリケーションのルートパスでantを実行、アプリケーションのコンパイル、ファイルの配置を行います。

#cd /Users/nyaago/workspace/struts-test
#ant
アプリケーションの起動

「Tomcat manager」のページからアプリケーションの起動を行います。

ブラウズからアクセス

ブラウザから「http://localhost:8080/test/hello/Hello!msg.action?message=hello」などのようにアクセスしてみる。うまくいっていれば、messageパラメータの値が表示されます。