Struts 2 Hello Worldの例(注釈付き、struts.xmlファイルなし)

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

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で構成する必要があります。

    <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.journaldev.struts2.actions</param-value>
    	</init-param>
    </filter>
    

    Struts 2は、次の方法でアクションクラスを検出します。

    • @Actionまたは@Actionsアノテーションが付けられたクラス。
    • Actionインターフェースを実装したクラスまたはActionSupportクラスを拡張したクラス。
    • 名前がActionで終わり、execute()メソッドを含むクラス。これらのクラスでは、命名規則が使用されてアクションと結果が決定されます。
  2. 命名規則: 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 を作成し、それを maven プロジェクトに変換します。最終的なプロジェクトは以下の画像のようになります。

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.journaldev.struts2.actions</param-value>
		</init-param>
	</filter>

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

</web-app>

init-param要素に注目してください。ここでは、Struts 2によってスキャンされるアクションクラスのパッケージを提供しています。

結果ページ

アプリケーションには3つの結果ページがあります。login.jsp

<%@ 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>

error.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>

welcome.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.journaldev.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 pankaj
 *
 */

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

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

package com.journaldev.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 pankaj
 *
 */
@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("pankaj".equals(getName()) && "admin".equals(getPwd()))
		return "SUCCESS";
		else return "ERROR";
	}
	
	//フォームパラメータを保持するためのJava Bean
	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アノテーションの例プロジェクトをダウンロード

Source:
https://www.digitalocean.com/community/tutorials/struts-2-hello-world-example-with-annotations-and-without-struts-xml-file