インストールからHelloWorld
EclipseのWTPプロジェクトを作成して、Struts2でHelloWorldをだすところまで。30分〜1時間ぐらいでできます。
少しはまったのは、struts.xmlの配置場所。デフォルトではWEB-INFの下ではなくてクラスパス上に配置する点に注意が必要です。
[前提]
[参考サイト]
プロジェクトソースツリー作成
Mave2でEclipseのwarプロジェクトを作成
mvn archetype:create -DgroupId=my.struts2 -DartifactId=colnago-struts2 -DarchetypeArtifactId=maven-archetype-webapp
Struts2のdependency定義をpom.xmlに記述
<dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>2.0.6</version> </dependency>
コンパイルコマンドを叩いて、必要なjarをローカルリポジトリにダウンロード。
cd D:\eclipse-ws\hello-struts2 mvn compile
cd D:\eclipse-ws\hello-struts2 mvn eclipse:eclipse -DdownloadSource=true -Dwtpversion=1.5
あとはEclipseにインポートすれば準備完了。
HelloWorld
Actionクラスをsrc/main/javaに作成。
package my.struts2.hello; import com.opensymphony.xwork2.ActionSupport; public class HelloWorld extends ActionSupport { public static final String MESSAGE = "Struts is up and running ..."; public String execute() throws Exception { setMessage(MESSAGE); return SUCCESS; } private String message; public void setMessage(String message) { this.message = message; } public String getMessage() { return message; } }
JSPファイルHelloWorld.jspをwebapp直下に作成。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Hello World!</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <h2><s:property value="message" /></h2> </body> </html>
struts.xml(1.xのstruts-config)をsrc/main/resourcesに配置。
このファイルは、クラスパス上におくことが必要です。WEB-INFの直下においても読んでくれないので注意。
※web.xmlのFilterDispatcherで設定が可能(試していないが)。
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <package name="tutorial" namespace="/tutorial" extends="struts-default"> <action name="HelloWorld" class="my.colnago.web.HelloWorld"> <result>/HelloWorld.jsp</result> </action> </package> </struts>
最後にweb.xmlの設定。
<?xml version="1.0" encoding="UTF-8"?> <web-app id="WebApp" 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>Archetype Created Web Application</display-name> <filter> <filter-name>struts</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> <init-param> <param-name>actionPackages</param-name> <param-value>my.struts2.hello</param-value> </init-param> </filter> <filter-mapping> <filter-name>struts</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
デプロイすると、"Struts is up and running ..."という文字が出ます。