Java: ServletからJSPへリクエストをフォワード

Sponsored Link

このエントリーをはてなブックマークに追加
はてなブックマーク - Java: ServletからJSPへリクエストをフォワード
Bookmark this on Delicious
Share on LinkedIn
Bookmark this on Livedoor Clip
Bookmark this on Yahoo Bookmark

目的

Servletで処理した結果をJSPファイルに転送し、HTMLを生成する。これによって、MVCモデルにおけるViewの分離ができる。

方法

protected void doGet(HttpServletRequest req, HttpServletResponse res)
	throws ServletException, IOException {
	ArrayList<String[]> table = new ArrayList<String[]>(); // 転送データ
<中略>
	req.setAttribute("table", table);
	req.getRequestDispatcher("jsp/view.jsp").forward(req, res);

上記のServletコード上のtableという変数をview.jspに渡したす場合、HttpServletRequest #setAttributeで変数を登録し、getRequestDispatcherとforwardでリクエストをフォワードする。

JSP側で登録した変数を取り出すには、下記のコードを用いる。

<% ArrayList<String[]> table = (ArrayList<String[]>)request.getAttribute("table"); %>

関連すると思われる記事:

Sponsored Link

This entry was posted in Java and tagged , , . Bookmark the permalink.

Facebook comments:

コメントを残す

メールアドレスが公開されることはありません。

次のHTML タグと属性が使えます: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>