首页 > 解决方案 > 如何强制 RequestMapping 重定向以尊重调用 URL 的协议。(HTTPS/HTTP)

问题描述

设想:

我对 swagger-ui 页面进行了重定向,以使其更易于访问。(骆驼让我难过)
当我在本地运行时,我使用的是 HTTP。
当我在测试服务器中运行时,我使用的是 HTTPS。
或者,我会很好地配置骆驼流(xml)来更改招摇页面的默认网址。

预期 - (https 重定向到 https)和(http 重定向到 http):

http://localhost:8080/swagger-ui--> http://localhost:8080/webjars/swagger-ui/index.html?url=/api/swagger&validatorUrl= https://remote.com/swagger-ui-->https://remote.com/webjars/swagger-ui/index.html?url=/api/swagger&validatorUrl=

实际 - https 和 http 重定向到 http:

http://localhost:8080/swagger-ui--> http://localhost:8080/webjars/swagger-ui/index.html?url=/api/swagger&validatorUrl= https://remote.com/swagger-ui-->http://remote.com/webjars/swagger-ui/index.html?url=/api/swagger&validatorUrl=

代码:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class SwaggerController {

    @RequestMapping("/swagger-ui")
    public String redirectToUi() {
        return "redirect:/webjars/swagger-ui/index.html?url=/api/swagger&validatorUrl=";
    }

    @RequestMapping("/swagger-ui.html")
    public String redirectToUi2() {
        return "redirect:/webjars/swagger-ui/index.html?url=/api/swagger&validatorUrl=";
    }
}
        <restConfiguration
                component="servlet"
                apiContextPath="swagger"
                contextPath="api"
                enableCORS="true"
                bindingMode="json">
            <dataFormatProperty key="prettyPrint" value="true"/>

            <!-- setup swagger api description -->
            <apiProperty key="base.path" value="api"/>
            <apiProperty key="api.version" value=".0.0.1"/>
            <apiProperty key="api.title" value="Some Forms"/>
            <apiProperty key="api.description" value="Description Here"/>
            <apiProperty key="api.contact.name" value="Contact here"/>
        </restConfiguration>

标签: springspring-mvcjava-8apache-camelswagger

解决方案


这是因为逻辑视图名称(例如“redirect:/myapp/some/resource”)会将您的调用重定向到当前的 Servlet 上下文,在您的情况下,上下文的方案是 HTTP。

您需要为这种情况实现不同的上下文(一种用于 HTTP,一种用于 HTTPS),然后您可以使用 camel-servlet 代理调用

上下文 1 - http:

from("servlet:myapp?matchOnUriPrefix=true")
.to("http://newURL?bridgeEndpoint=true&throwExceptionOnFailure=false")

上下文 2 - https:

from("servlet:myapp?matchOnUriPrefix=true")
.to("https://newURL?bridgeEndpoint=true&throwExceptionOnFailure=false")

推荐阅读