HttpServletResponse.sendRedirectによる URLのリダイレクト
2009/07/06 13:05Update
Java ServletのURLリダイレクト実装方法について解説します。
以下のその実装手順です。
Javaコード
ExternalUrlRedirectServlet.java
web.xml
.
ブラウザで
http://localhost:8080/redir?url=http%3A%2F%2Fwww.syboos.jp%2F
または
http://yourdomain.com/redir?url=http%3A%2F%2Fwww.syboos.jp%2F
へ入力してみます。
そして、http://www.syboos.jp/へリダイレクトされるはず。
Javaコード
ExternalUrlRedirectServlet.java
package mypackage;
import java.io.IOException;
import java.net.URLDecoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.syboos.pmplat.config.Configuration;
// redir?url=xxxxxxx
@SuppressWarnings("serial")
public class ExternalUrlRedirectServlet extends HttpServlet {
private static final String KEY_URL_PARAM = "url";
@SuppressWarnings("deprecation")
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String url = req.getParameter(KEY_URL_PARAM); //例:url=http%3A%2F%2Fwww.syboos.jp%2F
try {
//decode the url
url = URLDecoder.decode(url, "utf-8"); //url = http://www.syboos.jp/
} catch (Exception e) {
throw new ServletException("Error parameter with:" + req.getRequestURI());
}
res.sendRedirect(url); //http://www.syboos.jp/へリダイレクト
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
doGet(req, res);
}
}
web.xml
... <servlet> <servlet-name>ExternalUrlRedirectServlet</servlet-name> <servlet-class>mypackage.ExternalUrlRedirectServlet</servlet-class> </servlet> ... <servlet-mapping> <servlet-name>ExternalUrlRedirectServlet</servlet-name> <url-pattern>/redir</url-pattern> </servlet-mapping> ...
.
ブラウザで
http://localhost:8080/redir?url=http%3A%2F%2Fwww.syboos.jp%2F
または
http://yourdomain.com/redir?url=http%3A%2F%2Fwww.syboos.jp%2F
へ入力してみます。
そして、http://www.syboos.jp/へリダイレクトされるはず。
Sponsored Link
Comments
- Relative Articles
- Java開発及び実行環境の構築 | Linux篇 - (2008/08/31 20:34)
- Java開発及び実行環境の構築 | Windows篇 - (2008/08/31 21:18)
- 5分でJava Hello World! - (2008/08/31 22:13)
- Java言語の制御構文 - 条件分岐if/else/else if - (2008/10/01 21:30)
- Java言語の繰り返し制御構文 - for文 - (2008/10/03 18:22)
- Java言語の繰り返し制御構文 - do ... while文 - (2008/10/03 21:23)
- Java言語の繰り返し制御構文 - while文 - (2008/10/03 21:32)
- Java言語の基礎 - javacコマンドによるコンパイル - (2008/10/10 17:58)
- Java アクセス修飾子概要 - (2008/10/29 18:31)
- Javaアノテーション機能 概要 - (2009/02/12 13:06)