MVCパターン
MVCパターン・・・Webアプリケーションを構成する各種のプログラムを、モデル(Model)、ビュー(View)、コントローラ(Controller)の3種類に分類する。
Model
アプリケーションに必要なデータを保持し、データに対する操作を行う。(ビジネスロジック)
ショッピングサイトを例にすると、購入した商品の一覧を管理する処理や、合計金額を計算する処理など。
View
モデルのデータを取得し、ユーザーに表示する。主にJSPを使用する。
Controller
ユーザーからの入力を受取り、モデルの生成や設定を行う。主にサーブレットを使用する。
FrontControllerパターン
FrontControllerパターン・・・フロントコントローラーと呼ばれるサーブレットをWebアプリケーションの唯一の入り口として、すべてのリクエストを処理させる。
フロントコントローラーから、機能別のアクション(Javaクラス)を生成する。
MVCパターンとFrontControllerパターンの適用例
@WebServlet(urlPatterns={"*.action"}) public class FrontController extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter pw = resp.getWriter(); try { // フロントコントローラーが呼び出されたパスを取得 String path = req.getServletPath().substring(1); // 取得したパスの.aをAに、/を.に置換する。 String name = path.replace(".a", "A").replace('/', '.'); // アクションのクラス名を使って、アクションクラスのインスタンスを生成 Action action = (Action)Class.forName(name).newInstance(); // アクションクラスのexecuteメソッドを呼び出し、フォワード先のURLを取得 String url = action.execute(req, resp); // フォワードの実行 req.getRequestDispatcher(url).forward(req, resp); } catch (Exception e) { e.printStackTrace(pw); } } }
<p>検索キーワードを入力してください。</p> <form action="Search.action" method="post"> <input type="text" name="keyword"> <input type="submit" value="検索"> </form>
public class SearchAction extends Action { @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception { // search.jspで入力されたパラメータの取得 String keyword = request.getParameter("keyword"); // 検索の実行 ProductDAO dao = new ProductDAO(); List<Product> list = dao.search(keyword); // 検索結果をリクエスト属性に設定 request.setAttribute("list", list); // フォワード先のJSP名を返却 return "list.jsp"; } }
<p>追加する商品を入力してください。</p> <form action="Insert.action" method="post"> 商品名<input type="text" name="name"> 価格<input type="text" name="price"> <input type="submit" value="追加"> </form>
public class InsertAction extends Action { @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception { // リクエストパラメータの取得 String name = request.getParameter("name"); Integer price = Integer.parseInt(request.getParameter("price")); Product p = new Product(); p.setName(name); p.setPrice(price); ProductDAO dao = new ProductDAO(); dao.insert(p); List<Product> list = dao.search(""); request.setAttribute("list", list); return "list.jsp"; } }