2

我正在尝试解决如何从我的 webapp 重定向到另一台服务器,保留任何路径和 GET 变量。

例如

www.myapp.com/foo
foo.com

www.myapp.com/foo/bar
foo.com/bar

www.myapp.com/foo?bar=1
foo.com?bar=1

理想情况下,我只想使用类似的东西

<mvc:view-controller path="/foo/**" view-name="redirect:http://foo.com**" />
4

3 回答 3

1

我最终使用了过滤器。

从基础设施上看,这似乎是最简单的方法

过滤器实现:

public class DomainRedirectFilter extends OncePerRequestFilter {

    private String destinationDomain;
    private String sourceServletPath;

    @Override
    protected void doFilterInternal(HttpServletRequest request, 
             HttpServletResponse response, FilterChain filterChain)
             throws ServletException, IOException {
        String path = request.getServletPath();
        path = StringUtils.replace(path, getSourceServletPath(), "");
        if (request.getQueryString() != null) {
            path += '?' + request.getQueryString();
        }

        response.setHeader( "Location", getDestinationDomain() + path );
        response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
        response.setHeader( "Connection", "close" );
    }

web.xml

<filter>
    <filter-name>fooDomainRedirectFilter</filter-name>
    <filter-class>com.abc.mvc.util.DomainRedirectFilter</filter-class>
    <init-param>
        <param-name>destinationDomain</param-name>
        <param-value>http://foo.abc.com</param-value>
    </init-param>
    <init-param>
        <param-name>sourceServletPath</param-name>
        <param-value>/foo</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>fooDomainRedirectFilter</filter-name>
    <url-pattern>/foo/*</url-pattern>
    <url-pattern>/foo</url-pattern>
</filter-mapping>

我需要添加 2 个 url 模式以允许

/foo
/foo?id=1
/foo/bar
/foo/bar?id=1
于 2012-05-15T00:29:40.303 回答
1

Handler如果您使用类似的东西,您也可以这样做Jetty

public class DomainRedirectHandler extends HandlerWrapper {

    @Override
    public void handle(String target, Request baseRequest, HttpServletRequest request,
            HttpServletResponse response) throws IOException, ServletException {

        String hostName = request.getHeader("Host");
        if (hostName == null) {
            getHandler().handle(target, baseRequest, request, response);
            return;
        }

        // see if the host header has a domain name that we are redirecting
        hostName = hostName.toLowerCase();
        int index = hostName.indexOf(':');
        if (index >= 0) {
            // cut off the optional port suffix
            hostName = hostName.substring(0, index);
        }

        if (hostName.equals("some.domain.com")) {
            response.sendRedirect("https://some.other.domain.com");
        } else {
            getHandler().handle(target, baseRequest, request, response);
        }
    }
}

这显然需要在处理程序链中的内容处理程序之前生效。

于 2015-10-17T22:15:24.967 回答
0

这样的事情可能应该通过 Apache 使用虚拟主机来完成。

这是一些文档的链接:

http://httpd.apache.org/docs/2.0/vhosts/examples.html

于 2012-05-13T04:25:29.083 回答