自动将根路径重定向到Spring Boot上下文路径

时间:2019-05-17 14:51:23

标签: spring spring-boot

我正在使用application.properties文件中指定的Spring Boot上下文路径,并且效果很好

server.port=5000
server.context-path=/services

Spring Boot 2.0及更高版本

server.port=5000
server.servlet.context-path=/services

但是如何实现根的默认重定向,即“ /”到“ / services”

http://localhost:5000/services-很棒!

但是我希望http://localhost:5000/自动重定向到-> http://localhost:5000/services,以便最终用户应该能够访问域的根目录并自动重定向到上下文路径

当前访问根节点会抛出404(这对于默认配置是有意义的)

如何实现根目录(即“ /”)到上下文路径的自动重定向?

2 个答案:

答案 0 :(得分:2)

看来你不能简单地做到这一点。设置 server.servlet.context-path=/services 会将您的服务器的根路径设置为 /services。当您使用 / 重定向路径时 - 实际上,您正在使用路径 /services 进行重定向。 这是我尝试解决此问题的方法:

  • 如果您的应用程序(apache、nginx)前面有一个中间 Web 服务器 - 您可以在其设置中进行重定向。
  • 或者您可以将 server.servlet.context-path 设置替换为您自己的路径名,如下所示:
    app.endpoints.services_path=/servicesapplication.config
    Controller 中的 @RequestMapping("${app.endpoints.services_path}") 映射。
    然后从路径 / 重定向到 /services

例如,通过以下方式之一:

  • 使用重定向控制器
@Controller
public class RootRedirectController {
    @GetMapping(value = "/")
    public void redirectToServices(HttpServletResponse httpServletResponse){
        httpServletResponse.setHeader("Location", "/services");
        httpServletResponse.setStatus(302);
    }
}
  • 或者通过向 Spring Boot
  • 添加自定义
@Configuration
public class WebAppConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("forward:/services");
        // This method can be blocked by the browser!
        // registry.addRedirectViewController("/", "redirect:/services");
    }
}

希望这会有所帮助。抱歉,我的 Google 翻译。

答案 1 :(得分:0)

您有两种方法可以做到:

1。。在您的@SpringBootApplication引导类中,您可以扩展WebMvcConfigurerAdapter并覆盖addViewControllers方法。此方法可以重定向路由,您可以执行以下操作:

@SpringBootApplication
public class Application extends WebMvcConfigurerAdapter {

   @Override
   public void addViewControllers(ViewControllerRegistry registry) {
       registry.addRedirectViewController("/", "/services");
   }

   public static void main(String[] args) {
       SpringApplication.run(Application.class, args);
   }

}

2。。使用@Configuration创建一个配置文件,该文件扩展了WebMvcConfigurerAdapter并覆盖了上面提到的addViewControllers方法:

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

   @Override
   public void addViewControllers(ViewControllerRegistry registry) {
       registry.addRedirectViewController("/", "/services");
   }
}

注意: 如果您有一天要迁移到Spring 5,则会警告您WebMvcConfigurerAdapter已过时,您将不得不使用WebMvcConfigurer。 这里所有详细信息:

https://www.baeldung.com/web-mvc-configurer-adapter-deprecated