HttpServletResponse.sendRedirectによる URLのリダイレクト

2009/07/06 13:05Update
TAGS: Java | Servlet | サブレット | リダイレクト

Java ServletのURLリダイレクト実装方法について解説します。

以下のその実装手順です。

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/へリダイレクトされるはず。

有关作者
Syboos.jp編集長システム設計や開発、保守運営などを行ってます。オープンソース技術に興味があります。

Sponsored Link


Comments

用户名 (required)

Email (will not be published) (required)

URL

Evaluation