Java Spring Boot:如何将我的应用程序根目录(“/”)映射到index.html?

172

我该怎样将我的应用程序根目录 http://localhost:8080/ 映射到静态文件 index.html 上呢? 如果我导航到 http://localhost:8080/index.html,它可以正常工作。

我的应用程序结构如下:

dirs

我的 config\WebConfig.java 文件看起来像这样:

@Configuration
@EnableWebMvc
@ComponentScan
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("/");
        }
}

我尝试添加 registry.addResourceHandler("/").addResourceLocations("/index.html");,但它失败了。


2
也许这可以帮助你:https://dev59.com/3GIj5IYBdhLWcg3wTTcG - Udo Klimaschewski
3
它展示了如何映射 http://localhost:8080/appName,但这不是我需要的... - Shoham
1
WebMvcConfigurerAdapter已被弃用。 - user1346730
10个回答

180

如果您没有使用@EnableWebMvc注释,则可以直接使用它。当您这样做时,您关闭了Spring Boot在WebMvcAutoConfiguration中为您执行的所有操作。您可以删除该注释,或者您可以重新添加您关闭的视图控制器:

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/").setViewName("forward:/index.html");
}

14
根据参考文档:如果您想保留Spring Boot MVC功能,并且只想添加其他MVC配置(例如拦截器、格式化程序、视图控制器等),则可以添加自己的WebMvcConfigurerAdapter类型的@Bean,但不要添加 @EnableWebMvc - Dave Syer
1
这将在“/”处提供“index.html”。但是是否可能使浏览器实际上将URL从“/”更改为“/index.html”? - asmaier
19
好的,我明白了。如果您希望将URL从“/”更改为“/index.html”,请使用“redirect:/index.html”而不是“forward”,这样可以解决问题。 - asmaier
4
我没有使用@EnableWebMvc注解,也没有被重定向到index.html。 - Jelle den Burger
1
你可以尝试使用 redirect:/index.htmlforward 对我来说不起作用。此外,如果使用spring-boot,您可能只需要从@Configuration类中扩展WebMvcConfigurerAdapter,并覆盖addViewControllers方法。无需显式添加@Bean - membersound
显示剩余5条评论

45
Dave Syer的一个例子是答案评论
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class MyWebMvcConfig {

    @Bean
    public WebMvcConfigurerAdapter forwardToIndex() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                // forward requests to /admin and /user to their index.html
                registry.addViewController("/admin").setViewName(
                        "forward:/admin/index.html");
                registry.addViewController("/user").setViewName(
                        "forward:/user/index.html");
            }
        };
    }

}

10
在Spring 5中,使用WebMvcConfigurer而不是已弃用的WebMvcConfigurerAdapter。 - Andriy Kharchuk

35

如果它是一个Spring Boot应用程序。

Spring Boot会自动检测public/static/webapp文件夹中的index.html。如果你编写了任何控制器@Requestmapping("/"),它将覆盖默认功能,并且除非你输入localhost:8080/index.html,否则不会显示index.html


6
我创建了一个 src/main/resources/public/index.html 文件,它正常工作了!谢谢。 - James Watkins
那还是真的吗? - FearX
至今仍然是真实的。 - JeannotMn
哦,是的,我的同事在某个地方添加了一个无意义的@Requestmapping("/")。感谢您指出这一点。现在欢迎页面可以正常工作了。 - Man Coding

22
如果您使用最新的spring-boot 2.1.6.RELEASE和简单的@RestController注释,则无需执行任何操作,只需将index.html文件添加到resources/static文件夹下即可。
project
  ├── src
      ├── main
          └── resources
              └── static
                  └── index.html

然后访问你的应用程序的根URLhttp://localhost:8080

以上解决方案适用于Spring和Tomcat,你的HTTP请求自动映射到index.html文件的根/。但是如果你使用了@EnableWebMvc注释,那么你就需要手动完成这个步骤。在这种情况下,你有两个选择:

(1)移除该注释

(2)或者你可以重新添加你关闭的视图控制器

@Configuration
public class WebConfiguration implements WebMvcConfigurer {

   @Override
   public void addViewControllers(ViewControllerRegistry registry) {
       registry.addViewController("/").setViewName("forward:/index.html");
   }
   
}

希望这将对每个人有所帮助。


在我的情况下,它是可以工作的,但当我从Tomcat改成Undertow后突然停止工作。现在我需要一种方法来将/转发到我的index.html。 - Germán Faller
已更新上面的帖子,提供了可以帮助您的解决方案。 - zappee

18
@Configuration  
@EnableWebMvc  
public class WebAppConfig extends WebMvcConfigurerAdapter {  

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

}

同时,WebMvcConfigurerAdapter已被弃用。 - Maik

13

更新:2019年1月

首先,在资源下创建一个名为public的文件夹,并创建index.html文件。 使用WebMvcConfigurer代替WebMvcConfigurerAdapter。

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebAppConfig implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("forward:/index.html");
    }

}

如果这个程序无法正常运行,可能会出现什么问题?资源路径“resources/public/index.html”已存在;使用Java 13、Spring 2.2.2和Tomcat。 - JFFIGK

7
您可以添加一个 RedirectViewController,示例如下:
@Configuration
public class WebConfiguration implements WebMvcConfigurer {

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

6
在Spring Boot中,我总是将网页放在像public、webapps或views这样的文件夹中,并将其放置在src/main/resources目录中,就像你可以在application.properties中看到的那样。

Spring_Boot-Project-Explorer-View

这是我的application.properties文件:

server.port=15800
spring.mvc.view.prefix=/public/
spring.mvc.view.suffix=.html
spring.datasource.url=jdbc:mysql://localhost:3306/hibernatedb
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.format_sql = true

logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE

当您输入像 servername:15800 这样的URL并且Spring Boot占用Servlet分发器接收到此请求时,它将准确地搜索index.html,而且这个名称将区分大小写,就像spring.mvc.view.suffix一样,它可以是html、jsp、htm等等。
希望它能对大家有所帮助。

@ArifMustafa 在最近的Spring Boot版本中,我建议将网页放在模板中。 - ArifMustafa
你有相关的参考资料吗?我正在尝试创建一个带有Spring后端的React/Redux前端项目,但我不确定涉及到的最佳实践。 - mike

5

我遇到了同样的问题。Spring Boot 知道静态 html 文件的位置。

  1. 将 index.html 添加到 resources/static 文件夹中
  2. 然后删除根路径的完整控制器方法,比如 @RequestMapping("/")
  3. 运行应用程序并检查 http://localhost:8080(应该正常工作)

1
最终你的答案起作用了 :) - Abdeali Chandanwala

3
  1. index.html file should come under below location - src/resources/public/index.html OR src/resources/static/index.html if both location defined then which first occur index.html will call from that directory.
  2. The source code looks like -

    package com.bluestone.pms.app.boot; 
    import org.springframework.boot.Banner;
    import org.springframework.boot.Banner;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.builder.SpringApplicationBuilder;
    import org.springframework.boot.web.support.SpringBootServletInitializer;
    import org.springframework.context.annotation.ComponentScan;
    
    
    
    @SpringBootApplication 
    @EnableAutoConfiguration
    @ComponentScan(basePackages = {"com.your.pkg"}) 
    public class BootApplication extends SpringBootServletInitializer {
    
    
    
    /**
     * @param args Arguments
    */
    public static void main(String[] args) {
    SpringApplication application = new SpringApplication(BootApplication.class);
    /* Setting Boot banner off default value is true */
    application.setBannerMode(Banner.Mode.OFF);
    application.run(args);
    }
    
    /**
      * @param builder a builder for the application context
      * @return the application builder
      * @see SpringApplicationBuilder
     */
     @Override
     protected SpringApplicationBuilder configure(SpringApplicationBuilder 
      builder) {
        return super.configure(builder);
       }
    }
    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接