2007-06-10

すぐに始めるStruts2(フォームとバリデーション編)


相変わらず struts.xml無しでどこまで出来るかを検証中。
「できないこと」も色々(というか、かなり)あることがわかりつつあるが、ひとまずできるところまで紹介したい。
なお無設定運用の Struts2では、アクション名とアクションメソッド名の区切りを URL上で ! 文字を用いることで表現する(デフォルトのアクションメソッド名は execute)。
アクションクラスEmailActionの場合は、ブラウザから email!input.action がリクエストされると input() がコールされる。
単に email.action がリクエストされた場合は execute() がコールされる。

EmailAction.java

import org.apache.struts2.config.Result;
import org.apache.struts2.config.Results;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.validator.annotations.EmailValidator;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.ValidatorType;

@Results({
@Result(name="input",value="input.jsp"),
@Result(name="success",value="success.jsp")
})

public class EmailAction extends ActionSupport {

private static final long serialVersionUID = 1L;

private String email;

/**
* @return the email
*/

public String getEmail() {
return email;
}

/**
* @param email the email to set
*/

@EmailValidator(type = ValidatorType.FIELD,
message="メールアドレスが正しくない様です。")
@RequiredStringValidator(type = ValidatorType.FIELD,
message="メールアドレスを入力して下さい。")
public void setEmail(String email) {
this.email = email;
}

public String input()
{
// フォームの初期値設定などをここでする。不要な場合はこのメソッド自体省略しても良い
// (ActionSupport#input()で { return "input" } が実装されているから)
return "input";
}

public String execute()
{
// バリデーションが通過したのちにこのメソッドがコールされる。
// ここでユーザの入力内容をデータベースに保存するなどの処理をする

return "success";
}

}

input.jsp

<%@page contentType="text/html;charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<s:head/>
</head>
<body>
<h1>アドレスを追加する</h1>

<s:actionerror />
<s:form>
<%-- s:textfieldのようなUIタグを使うとバリデーションエラーが自動で表示される --%>
<s:textfield label="メールアドレス" name="email"/>
<s:submit />
</s:form>

</body>
</html>

フォームに表示すべきエラーにはアクションエラーとフィールドエラーがある。
フィールドエラー(メールアドレスが正しくありません、など)は UIコンポーネントと
共に自動的に表示されるが、アクションエラー(特定のフィールドに属さないエラー)は
明示的に <s:actionerror/>タグで表示場所を指定する必要がある。もしあればだが。

参考リンク

Apache Struts 2 Documentationより
Annotations
Struts Tags
Class ActionSupport

サンプルアプリケーションの中に収録されているなかなか役に立つ文書
A Walking Tour of the Struts 2 MailReader Application

ラベル:

0 件のコメント:

コメントを投稿

<< ホーム