最終更新日:190526 原本2015/12/15

Java Servlet の リダイレクトとフォワード

Java Servlet のリダイレクトとフォワードを試してみたのでメモ。

環境

  • Windows7

    • Java 8.0.6001

    • NetBeans 8.02

    • Tomcat 8

リダイレクトとフォワード

リダイレクトとフォワードとは、 画面から画面へ移動するための方法である。

次の画面へのリクエストを投げた時に、 Tomcatは、 フォワードまたはリダイレクトで、 リクエストを返すことができる。

リダイレクトとは

画面移動する指示を「こっそり」クライアントに出す。

URLはリダイレクト先に変更される。

リダイレクトの仕組み

画面Aのリダイレクト先が画面Bの場合:
画面Aのリクエストがあった場合、 Tomcatが画面Bへ(こっそりリダイレクト)して、 レスポンスを返す。

(昔のIEなどでは、リダイレクトがされたとき、 カチッと音が鳴っていた。)

リダイレクトはどんなときに使うか

    例:
  • 別のWebサイトを表示したいとき

  • (サーバ移転などで)同じサイトだが新しくページを表示するとき

リダイレクト先の指定方法

doGet()doPost()メソッドの response引数の中のsendRedirect("移動先")メソッドを使う。


response.sendRedirect("移動先");

フォワードとは

サーバが画面の作成と表示を行う。

URLは変わらない。

フォワードの仕組み

画面Aのフォワード先を画面Bへ指定している場合
画面Aをリクエストした場合、 Tomcatが次の画面を準備 して、 画面B をレスポンスする。

URLは変わらない。

フォワードはどんなときに使うか

    例:
  • 同じサイト内のページを表示するとき

  • ※リダイレクトのようにほかのサイトには移動できない

  • ※同じサイト内であればリダイレクトよりフォワードを使うようにする

フォワード先の指定方法

リダイレクトより少し複雑になる。


ServletContext context = request.getServletContext();
RequestDispatcher rd = context.getRequestDsipatcher("移動先");
rd.forward(request, response);

Webサイトの情報「コンテキスト」

request.getServletContext() メソッドで、 指定された URL に対応する ServletContext オブジェクトを返す。

ServletContextには、 Servlet(Webコンテナ)の設定情報が詰まっている。

移動先を決定する「ディスパッチ」

コンテキスト内の移動先を、 「コンテキストルート」以降から指定する。


RequestDispatcher rd = context.getRequestDsipatcher("/forward.jsp");

コンテキストルートとは、 Sampleという名前のプロジェクトを作った場合、


http://localhost:8080/Sample/forward.jsp

の中の、http://localhost:8080/Sample がコンテキストルートになる。

リダイレクトは絶対パス、相対パスどちらでもok。

フォワードは、コンテキストルートからの移動先を指定する。

フォワードとリダイレクトの違い

 リダイレクトフォワード
リクエスト/レスポンス回数 2 1
外部サイトへの移動 できる できない
処理速度 遅い(と言われている) 速い
URL 変わる 変わらない

リダイレクトのサンプル

コード

<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>Java Redirect</title>
</head>
<body>
<p>Redirectしました.</p>
</body>
</html>
view raw redirect.jsp hosted with ❤ by GitHub
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns = {"/RedirectSample"})
public class RedirectSample extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* コンストラクタ.
*/
public RedirectSample() {
super();
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 指定したパスにリダイレクトさせる
response.sendRedirect("./redirect.jsp");
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
view raw RedirectSample.java hosted with ❤ by GitHub

Redirectするサンプル

実行結果

「http://localhost:8080/RedirectForward/RedirectSample」にアクセス

リダイレクト前

リダイレクトするとURLが変わる。 (「http://localhost:8080/RedirectForward/redirect.jsp」へ リダイレクトされる。)

「http://localhost:8080/RedirectForward/RedirectSample」にアクセスすると「http://localhost:8080/RedirectForward/redirect.jsp」へリダイレクトされる

リダイレクト後

フォワードのサンプル

コード

<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>Java Forward</title>
</head>
<body>
<p>Forward しました.</p>
</body>
</html>
view raw forward.jsp hosted with ❤ by GitHub
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ForwardSample extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* コンストラクタ.
*/
public ForwardSample() {
super();
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//processRequest(request, response);
// このWebアプリケーションの設定を取得
ServletContext context = request.getServletContext();
// このWebアプリケーション内にあるページ(移動先のページ)を決定
RequestDispatcher rd = context.getRequestDispatcher("/forward.jsp");
// 移動先のページに移動
rd.forward(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
view raw ForwardSample.java hosted with ❤ by GitHub

Forwardするサンプル

実行結果

「http://localhost:8080/RedirectForward/ForwardSample」へアクセスすると

フォワード前

フォワードは、URLは変わらない。 (「forward.jsp」の内容が「http://localhost:8080/RedirectForward/ForwardSample」へ表示されている。)

「http://localhost:8080/RedirectForward/ForwardSample」へアクセスすると「forward.jsp」の内容がフォワードされる。

フォワード後

まとめ

  • ・Servletからの画面移動の方法は、 「フォワード」と「リダイレクト」の2パターンある。

  • 「リダイレクト」は、 画面を移動させるための処理

  • 「フォワード」は、 画面を表示させるための処理