アノテーションを使用したStruts 2のHello Worldの例で、struts.xmlファイルなしで。

これはStruts 2チュートリアルシリーズの2番目の記事です。もし直接ここに来たのであれば、前の投稿もチェックすることをおすすめします。前回のチュートリアルでは、Struts 2のアーキテクチャ、コンポーネントについて説明し、XMLベースの構成(struts.xml)を使用してシンプルなStruts 2ウェブアプリケーションを作成しました。このチュートリアルでは、注釈や命名規則を使用して、Strutsの構成ファイルを完全に回避する方法を見ていきます。

ストラット2のコンベンションの概念

Struts 2では、アクションクラスと結果クラスを見つけるために2つの方法論が使用されています。これらの方法論のいずれかを使用するには、struts2-convention-plugin APIを使用する必要があります。通常のWebアプリケーションをお持ちの場合は、そのjarファイルをダウンロードしてWebアプリケーションのlibディレクトリに配置してください。Mavenプロジェクトの場合は、以下のように依存関係を単純に追加することができます。

<dependency>
	<groupId>org.apache.struts</groupId>
	<artifactId>struts2-convention-plugin</artifactId>
	<version>2.3.15.1</version>
</dependency>
    1. スキャン:この方法では、アクションクラスをスキャンする必要のあるパッケージを指定します。Struts 2フィルターのweb.xmlで以下のように設定する必要があります。

 

    1. struts2

 

    1. org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter

 

    1. actionPackages com.scdev.struts2.actions

 

Struts 2は以下の方法でアクションクラスを見つけます。

@Actionまたは@Actionsアノテーションで注釈付けられたクラス
Actionインタフェースを実装したりActionSupportクラスを拡張したりするクラス
クラス名がActionで終わり、execute()メソッドを含むクラス。これらのクラスでは、アクションと結果を決定するために命名規則が使用されます。

命名規則:Struts 2は、Actionで終わるクラス名に対して自動的にアクションを作成します。アクション名は、Actionの接尾辞を削除し、最初の文字を小文字に変換することで決定されます。したがって、クラス名がHomeActionである場合、アクションは「home」になります。これらのクラスが@Resultで結果を提供するように注釈付けされていない場合、結果ページはWEB-INF/contentディレクトリ内を探され、名前は{action}-{return_string}.jspである必要があります。したがって、HomeActionアクションクラスが「success」を返す場合、リクエストはWEB-INF/content/home-success.jspページに転送されます。命名規則のみを使用すると非常に混乱する可能性があり、他のアクションクラスに同じJSPページを使用することはできません。これを避けるために、注釈ベースの構成を使用するようにする必要があります。

今、注釈を使用してHello WorldのStruts 2アプリケーションを作成する準備が整いました。Struts 2の設定ファイルは必要ありません。EclipseのStruts2AnnotationHelloWorldでダイナミックWebプロジェクトを作成し、Mavenプロジェクトに変換します。最終的なプロジェクトは以下の画像のようになります。

メイブンの設定

pom.xmlにはstruts2-coreとstruts2-convention-pluginの依存関係を追加しました。最終的なpom.xmlコードは以下の通りです。

<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>Struts2AnnotationHelloWorld</groupId>
	<artifactId>Struts2AnnotationHelloWorld</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>

	<dependencies>
		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-core</artifactId>
			<version>2.3.15.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-convention-plugin</artifactId>
			<version>2.3.15.1</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.3</version>
				<configuration>
					<warSourceDirectory>WebContent</warSourceDirectory>
					<failOnMissingWebXml>false</failOnMissingWebXml>
				</configuration>
			</plugin>
		</plugins>
		<finalName>${project.artifactId}</finalName>
	</build>
</project>

デプロイメントディスクリプタの構成

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
	xmlns="https://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<display-name>Struts2AnnotationHelloWorld</display-name>

	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
		<init-param>
			<param-name>actionPackages</param-name>
			<param-value>com.scdev.struts2.actions</param-value>
		</init-param>
	</filter>

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

</web-app>

struts 2 がスキャンするアクションクラスのパッケージを指定する init-param 要素に注意してください。

結果ページ

私たちのアプリケーションには、ログイン.jspという3つの結果ページがあります。

<%@ page language="java" contentType="text/html; charset=US-ASCII"
    pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<%-- Using Struts2 Tags in JSP --%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Login Page</title>
</head>
<body>
<h3>Welcome User, please login below</h3>
<s:form action="login">
	<s:textfield name="name" label="User Name"></s:textfield>
	<s:textfield name="pwd" label="Password" type="password"></s:textfield>
	<s:submit value="Login"></s:submit>
</s:form>
</body>
</html>

エラーページ.jsp

<%@ page language="java" contentType="text/html; charset=US-ASCII"
    pageEncoding="US-ASCII"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Error Page</title>
</head>
<body>
<h4>User Name or Password is wrong</h4>
<s:include value="login.jsp"></s:include>
</body>
</html>

ようこそ.jsp

<%@ page language="java" contentType="text/html; charset=US-ASCII"
    pageEncoding="US-ASCII"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Welcome Page</title>
</head>
<body>
<h3>Welcome <s:property value="name"></s:property></h3>
</body>
</html>

さて、アクションクラスを作成しましょう。アクションクラスはアクションと結果のページを設定するためにアノテーションを付けます。

注釈付きのアクションクラス

package com.scdev.struts2.actions;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Namespaces;
import org.apache.struts2.convention.annotation.Result;

import com.opensymphony.xwork2.ActionSupport;

/**
 * An empty class for default Action implementation for:
 * 
 *  <action name="home">
 *		<result>/login.jsp</result>
 *	</action>
 * HomeAction class will be automatically mapped for home.action
 * Default page is login.jsp which will be served to client
 * @author scdev
 *
 */

@Namespaces(value={@Namespace("/User"),@Namespace("/")})
@Result(location="/login.jsp")
@Actions(value={@Action(""),@Action("home")})
public class HomeAction extends ActionSupport {
}

HomeActionというクラスは、リクエストをlogin.jspページに転送するという唯一の目的を持つ空のクラスであることに注意してください。

package com.scdev.struts2.actions;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Namespaces;
import org.apache.struts2.convention.annotation.Result;

/**
 * Notice the @Action annotation where action and result pages are declared
 * Also notice that we don't need to implement Action interface or extend ActionSupport
 * class, only we need is an execute() method with same signature
 * @author scdev
 *
 */
@Action(value = "login", results = {
		@Result(name = "SUCCESS", location = "/welcome.jsp"),
		@Result(name = "ERROR", location = "/error.jsp") })
@Namespaces(value={@Namespace("/User"),@Namespace("/")})
public class LoginAction {

	public String execute() throws Exception {
		if("scdev".equals(getName()) && "admin".equals(getPwd()))
		return "SUCCESS";
		else return "ERROR";
	}
	
	//Java Bean to hold the form parameters
	private String name;
	private String pwd;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
}

@Action、@Actions、@Result、@Namespace、および@Namespacesの注釈の使用に注意してください。その使用方法は自己説明的です。今、アプリケーションを実行すると、以下の応答ページが表示されます。もし、前回の投稿を読んだことがあるならば、それはstruts.xmlの設定で同じアプリケーションを開発したものですが、ほぼ同じという点に注目してください。唯一の変更点は、アプリケーションのアクションクラスと結果ページを接続する方法です。

「Struts2アノテーションのサンプルプロジェクトをダウンロードしましょう。」

コメントを残す 0

Your email address will not be published. Required fields are marked *