0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

📘 Vol.10.4:Actionとの連携実装(Struts2との融合)

Last updated at Posted at 2025-05-25

DTO・DAO・DB接続クラスの設計を学んだ方へ。
本記事では、それらのクラスを実際に Struts2のActionクラスとどのように連携させるか を徹底解説します!


🔰 1. Struts2におけるActionクラスの役割

Actionクラスは、Struts2におけるMVCのControllerに相当します。

  • フォーム入力やURLリクエストの受け口
  • DAO/Serviceなどを使ってビジネスロジックを実行
  • DTOなどを介して、結果データをJSP(View)に渡す

🧩 2. DTO・DAOとの連携の流れ

基本構成は以下の通り:

Action → DAO → DB → DTO → View(JSP)

例:UserListAction.java

public class UserListAction extends ActionSupport {
    private List<User> users;

    public String execute() {
        UserDao dao = new UserDaoImpl();
        users = dao.findAll(); // DAOからDTOのList取得
        return SUCCESS;
    }

    public List<User> getUsers() {
        return users; // JSPからEL式で取得可能
    }
}

🧪 3. 典型的な実装例:ユーザ一覧表示

🎯 Actionクラス

public class UserListAction extends ActionSupport {
    private List<User> userList;

    public String execute() {
        UserDao dao = new UserDaoImpl();
        userList = dao.findAll();
        return SUCCESS;
    }

    public List<User> getUserList() {
        return userList;
    }
}


🌐 4. struts.xml の設定

<action name="userList" class="com.example.action.UserListAction">
    <result name="success">/view/UserList.jsp</result>
</action>

userList.action にアクセスすると、UserListAction が実行され、UserList.jsp が表示されます。


📄 5. JSPでDTOを表示する

<table>
  <tr><th>ID</th><th>名前</th><th>Email</th></tr>
  <s:iterator value="userList" var="user">
    <tr>
      <td><s:property value="#user.userId"/></td>
      <td><s:property value="#user.username"/></td>
      <td><s:property value="#user.email"/></td>
    </tr>
  </s:iterator>
</table>

getUserList() の戻り値を userList としてJSPで使えます。


🛠 6. よくある連携ミスとその対策

問題例 原因と対策
NullPointerException DAOを new し忘れ/DIが未設定
JSPでデータが表示されない DTOに getter が未実装
Actionが呼ばれない struts.xml の name or class が誤記

🧾 まとめ

要素 役割
Action ユーザーの入力を受けて処理・JSPへの橋渡し
DAO DBへのアクセス責任を持つクラス
DTO データ保持用のJavaBean
JSP DTOからデータを受け取って表示

🔜 次回予告(Vol.10.5)

📘 Vol.10.5 では…

🧪 DAO・DTOのテスト設計(JUnitやH2活用) を解説予定!
ユニットテストで品質の高い開発を目指しましょう💪


以上、Struts2 × DAO/DTO の連携完全ガイドでした!
次回もどうぞお楽しみに 😄


✨ シリーズまとめ(Vol.10.x バリデーション編)


0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?