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?

自分用jspにチャレンジ ~MVC~

Posted at

MVCアーキテクチャ

Model モデル

役割

アプリケーションのビジネスロジックやデータ処理を担当する。
DBとのやり取りや処理ロジックを含む。
例:
・DBからユーザー情報を取得、更新する処理
・ユーザー名が正しいかを検証する処理
javaクラスの例

UserModel.java
public class UserModel {

    public UserDTO getUserById(int id) {

    // DBからユーザー情報を取得
    }
}

Controller コントローラー

役割

ユーザーからのリクエストを受け取り、適切な処理(Modelの呼び出し)や画面遷移を制御する
例:
・login.jspから送信されたユーザー名とパスワードを受け取り、認証を行い、静甲ならmypage.jspに、失敗ならlogin.jspに戻す
javaクラスの例(Servlet)

HttpServlet.java
@WebServlet("/login")
public class LoginController extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
        String user = request.getParameter("username");
        String pass = request.getParameter("password");
        
        UserModel model = new UserModel();
        boolean result = model.checkLogin(user, pass);
        
        if (result) {
        
            response.sendRedirect("mypage.jsp");
        } else {
        
            response.sendRedirect("login.jsp");
        }
    }
}

DTO (Data Transfer Object)

役割

データを格納するためのシンプルな入れ物。ModelとControllerやViewでのデータのやり取りを簡潔に行うために使われる。
例:
・ユーザーのID, 名前, メールアドレスなどの情報を1つのオブジェクトにまとめる
javaクラスの例

UserDTO.java
public class UserDTO {

    private int id;
    private String name;
    private String email;

    // getter, setter
    public int getId() {

        returnid;
    }

    public void setId(int id) {

        this.id = id;
    }

    public String getName() {

        return.name;
    }

    public void setName(String name) {

        this.name = name;
    }

    public String getEmail() {

        return email;
    }

    public void setEmail(String email) {

        this.email = email;
    }
}

View ビュー

役割

ユーザーに表示される画面の見た目を担当する。jspファイルで記述され、HTMLとjavaを組み合わせて動的にページを生成する
例:
・ログイン画面、ユーザー情報表示画面、エラーメッセージの表示など
jspの例

sample.jsp
<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<body>
    <h1>ようこそ、<%= request.getAttribute("username") %>さん!</h1>
</body>
</html>

全体の流れ(MVCの関係図)

  1. ユーザーがホーム送信(View)
  2. Controllerがリクエストを受け取る
  3. Modelに処理を依頼
  4. 結果をDTOに詰めてViewに渡す
  5. View(jsp)が結果を画面に表示

おわりに

railsの経験を生かしてまずはjspでかんたnTodoアプリの作成に挑戦してみたいと思います

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?