Struts1と2の内容が混在しています。完全に自分用メモです。
Struts2
参考サイト
リクエスト送信→受け取り→レスポンスまでの流れ
jspのformタグからリクエスト送信
index.jsp
<body> <s:form action="message"> <s:textfield name="age"/> <s:submit value="年齢送信"/> </body>
s:~~~はStrutsのタグライブラリ。
- s:form action="message":struts.xmlのaction name="message"が呼び出される
- <s:textfield name="age"/>:アクションクラスのprivate int ageに代入される
struts.xmlで動きを制御
<?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> <!-- アクションのパッケージ定義 --> <package name="default" extends="struts-default"> <action name="message" class="sample.MessageAction" method="ageMessage"> <result name="fortune">/view/sample/fortune.jsp</result> <result name="good">/view/sample/good.jsp</result> </action> </package> </struts>
- action name="message":呼び出し用の名前
- class="sample.MessageAction":呼び出されるクラス
- method="ageMessage":呼び出されるメソッド
- <result name="fortune" /view/sample/fortune.jsp:return "fortune"すると呼び出されるjsp
- <result name="good" /view/sample/good.jsp:return "good"すると呼び出されるjsp
アクションクラスが呼び出される
MessageAction.java
package sample; public class MessageAction { private int age; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String ageMessage() { if (this.age >= 70) { return "good"; } return "fortune"; } }
struts.xmlに対応したActionクラス、Actionメソッドを作る。
- private int age:index.jspの<s:textfield name="age"/>の値が入る。勝手にgetter/setterが動くらしい
- return "good":/view/sample/good.jspが呼び出される
- return "fortune":/view/sample/fortune.jspが呼び出される
リクエストで受け取った値をjspで表示
good.jsp
<body> <s:property value="age"/>才。よく生きましたね。<br>あなたの人生に幸あらんことを。 </body>
fortune.jsp
<body> <s:property value="age"/>才、あなたの人生に幸あらんことを。 </body>
簡易まとめ
jspでAction名「message」を指定して呼び出す
→該当のActionメソッドが呼び出される
→Actionメソッドがreturn forutune or good する
→struts.xml内でresultName「'fortune' or 'good'」を検索
→jsp内の<s:property value="age"/>は、Actionクラスのage変数から取ってくる
Struts1
参考サイト
概要を学ぶならここ↓
Strutsフレームワークの「枠組み」を学ぶ:Strutsを使うWebアプリケーション構築術(2)(1/2 ページ) - @IT
もうちょっと踏み込んだ概要↓
【Struts入門】今さらStruts1.3.10を勉強したのでまとめてみた【初心者向け】 - Qiita
コード書くときの参考はここ↓
忘れっぽいエンジニアのJakarta Strutsリファレンス
コード書くときの参考2はここ↓
Javaの道>オープンソース
環境構築
下記サイトからstruts-1.3.10-all.zipをダウンロードして解凍。
https://struts.apache.org/releases
appsフォルダ内の「struts-blank-1.3.10.war」をEclipseからwarファイルのインポートを実行する。
インポートしたプロジェクトを実行して下記画面が出たらOK
あとは自由に中身を作り変えましょう。
jsp
下記コードはクライアントサイドとサーバーサイドの両方のバリデーションが有効。
クライアントサイドのバリデーションが優先される。
サーバーサイドのバリデーションメッセージを見る場合は「html:javascript~」と「onsubmit=~」を消す。
・index.jsp
<%@page contentType="text/html; charset=UTF-8"%> <%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%> <%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%> <%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%> <% request.setCharacterEncoding("UTF-8"); %> <body> <!-- クライアントサイドのバリデーションを有効にしている --> <html:javascript formName="SampleForm" /> <!-- クライアントサイドのバリデーションを有効にしている2 onsubmit="return validate「Formクラス名」(this)" --> <html:form action="/SampleAction.do" onsubmit="return validateSampleForm(this)"> <bean:message key="index.nameText" /> <html:text property="name" /> <!-- classはstyleClass。 idはstyleId で付与する --> <html:text property="age" styleClass="ageClass"/> <html:submit value="年齢送信" styleId="aaa" /> </html:form> <!-- サーバーサイドのバリデーションメッセージ部分。 クライアントサイドのバリデーションを消すとこっちが動作する --> <html:errors property="name"/> <html:errors property="age" /> </body>
Welcom.jsp
<%@ page isELIgnored="false" %><!-- EL式を有効にする --> <%@page contentType="text/html; charset=UTF-8" %> <% request.setCharacterEncoding("UTF-8"); %> <%@page contentType="text/html; charset=UTF-8" %> <%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %> <%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %> <%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %> <html:html> <head> <title>welcome</title> </head> <h3><bean:message key="welcome.heading"/></h3> <!-- SampleForm.nameとSampleForm.ageを取得 --> <bean:parameter name="name" id="na"/> <bean:parameter name="age" id="ag"/> ${sampleForm.name}<br><!-- ここだけEL式 --> <%= na %><br> <%= ag %><br> </body> </html:html>
Actionクラス
MVCで言うところのController。Actionクラスを継承する。
下記がActionクラスとActionメソッドの基本の書き方。
package controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import model.SampleForm; public class SampleAction extends Action { public ActionForward execute (ActionMapping map, ActionForm form, HttpServletRequest request, HttpServletResponse response) { SampleForm sampleForm = (SampleForm)form; request.setAttribute("sampleForm", sampleForm); // ここはEL式使わないならなくてOK return map.findForward("success"); } }
ActionFormクラス
MVCのModelクラス。ValidatorFormクラスを継承。
package model; import org.apache.struts.validator.ValidatorForm; public final class SampleForm extends ValidatorForm { private String name; private int age; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public void setName(String name) {this.name=name;} public String getName() {return name;} }
WebページのForm要素にあるパラメータ値を格納するためのJavaBean。
引用元:2. ActionForm | TECHSCORE(テックスコア)
ValidatorFormを継承してFormクラスを作るとHTMLのformタグから送られた値をget/setできる。
なおかつValidationも活用できる。
struts-config.xml
の重要な部分だけ。
※私の環境ではstruts-configを変更する度にプロジェクトのリフレッシュが必要でした。
下記サイトの画像による説明がめっちゃわかりやすいのでそれを見よう↓
参考:Strutsフレームワークの「枠組み」を学ぶ:Strutsを使うWebアプリケーション構築術(2)(2/2 ページ) - @IT
- form-beans:Formクラスの場所と名前を定義するだけ。
- action-mappings:アクションの定義
- path:呼び出すアクションクラス。
- name:アクションクラスが実行された時に実行されるアクションフォームBeanの名前
- type:アクションクラスの完全修飾名
- scope:request/sessionのどちらかを設定できる。
- validate:バリデーションの有効化。
- input:バリデーションエラーの場合に遷移するページを指定。
- forward
- name:Actionクラスでreturn "success"すると呼び出される。
- path:呼び出されるファイル
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd"> <struts-config> <form-beans> <form-bean name="SampleForm" type="model.SampleForm" /> </form-beans> <global-exceptions> </global-exceptions> <global-forwards> <!-- Default forward to index.do --> <forward name="index" path="/index.do"/> </global-forwards> <action-mappings> <action path="/SampleAction" type="controller.SampleAction" name="SampleForm" scope="request" validate="true" input="/index.jsp"> <forward name="success" path="/pages/Welcome.jsp"/> </action> </action-mappings> <plug-in className="org.apache.struts.validator.ValidatorPlugIn"> <set-property property="pathnames" value="/org/apache/struts/validator/validator-rules.xml, /WEB-INF/validation.xml"/> </plug-in> </struts-config>
validation.xml
各所の意味はこちらを参考に↓
Javaの道:Struts(17.Validator)
<?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE form-validation PUBLIC "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.3.0//EN" "http://jakarta.apache.org/commons/dtds/validator_1_3_0.dtd"> <form-validation> <global> <!-- An example global constant <constant> <constant-name>postalCode</constant-name> <constant-value>^\d{5}\d*$</constant-value> </constant> end example--> </global> <formset> <form name="SampleForm"> <field property="name" depends="required"> <arg key="index.nameText" /> </field> <field property="age" depends="minlength"> <arg0 key="index.ageText" /> <arg1 key="${var:minlength}" resource="false"/> <!-- ${var:minlength}は変数。<var-value name="value">の値「4」をとってくる。 resource="false"でmessage.propertiesの参照をとめる --> <var> <var-name>minlength</var-name> <var-value name="value">4</var-value> </var> </field> </form> </formset> </form-validation>
MessageResource.properties
# -- standard errors -- errors.header=<UL> errors.prefix=<LI> errors.suffix=</LI> errors.footer=</UL> # -- validator -- errors.invalid={0} is invalid. errors.maxlength={0} can not be greater than {1} characters. errors.minlength={0} can not be less than {1} characters. errors.range={0} is not in the range {1} through {2}. errors.required={0} is required. errors.byte={0} must be an byte. errors.date={0} is not a date. errors.double={0} must be an double. errors.float={0} must be an float. errors.integer={0} must be an integer. errors.long={0} must be an long. errors.short={0} must be an short. errors.creditcard={0} is not a valid credit card number. errors.email={0} is an invalid e-mail address. # -- other -- errors.cancel=Operation cancelled. errors.detail={0} errors.general=The process did not complete. Details should follow. errors.token=Request could not be completed. Operation is not in sequence. # -- index -- index.nameText=name index.ageText=age
ActionMessagesクラス
ページにメッセージを渡すクラス。
エラーメッセージ表示とかに使う。
ActionErrorsというクラスもあり、使い方もほぼ同じ。
メッセージ本文はmessages.propertiesとかから取得。
messages.add(プロパティ, ActionMessage);// メッセージを追加 saveMessages(request, messages); // メッセージを保存
参考:いまさらながらStruts – ActionMessages | 雑廉堂の雑記帳
ActionMappingクラス
struts-config.xmlでアクション名とか決めてる所。
ActionMapping.getAttributeとかでname要素を取得できるんだと思う。
// こんな感じでアクションメソッドの引数にとりあえず入れておく public ActionForward executeAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
参考:Strutsリファレンス<action-mapping>
.doの謎
.doが付いてたり、付いてなかったりで混乱した。
- <html:form>要素内だと.doいらない。自動でつく。
- その他は.doいる。
.doをつけないとアクションサーブレットが呼ばれない。
呼ばれないとstruts-config.xmlを経由しないのでAction呼べない。
つまり直リンクで画面遷移しかできない。
参考↓ 下のほう、まとめの上あたりに書いてある
簡易まとめ
jspでActionのpath名「/SampleAction」で呼び出す
→struts.xml内で「/SampleAction」を検索
→該当のActionクラスのexecuteメソッドが呼び出される
→同時に「name="SampleForm"」の部分で、SampleFormクラスに値がセットされる。
→Actionメソッドがreturn success する
→struts.xml内でforward name「success」を検索
→Welcome.jspに遷移
もっと新しい技術を触りたいなあ(´;ω;`)