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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27381781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 04:16:25  来源:igfitidea点击:

Java Spring Boot: How to map my app root (“/”) to index.html?

javaspringspring-boot

提问by Shoham

I'm new to Java and to Spring. How can I map my app root http://localhost:8080/to a static index.html? If I navigate to http://localhost:8080/index.htmlits works fine.

我是 Java 和 Spring 的新手。如何将我的应用程序根映射http://localhost:8080/到静态index.html?如果我导航到http://localhost:8080/index.html它的工作正常。

My app structure is :

我的应用程序结构是:

dirs

目录

My config\WebConfig.javalooks like this:

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

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

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

I tried to add registry.addResourceHandler("/").addResourceLocations("/index.html");but it fails.

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

采纳答案by Dave Syer

It would have worked out of the box if you hadn't used @EnableWebMvcannotation. When you do that you switch off all the things that Spring Boot does for you in WebMvcAutoConfiguration. You could remove that annotation, or you could add back the view controller that you switched off:

如果您没有使用@EnableWebMvc注释,它会开箱即用。当你这样做时,你关闭了 Spring Boot 在WebMvcAutoConfiguration. 您可以删除该注释,或者您可以重新添加您关闭的视图控制器:

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

回答by justin

An example of Dave Syer's answer:

戴夫·赛尔 (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");
            }
        };
    }

}

回答by Krish

if it is a Spring boot App.

如果是 Spring Boot App。

Spring Boot automatically detects index.html in public/static/webapp folder. If you have written any controller @Requestmapping("/")it will override the default feature and it will not show the index.htmlunless you type localhost:8080/index.html

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

回答by Rodrigo Ribeiro

@Configuration  
@EnableWebMvc  
public class WebAppConfig extends WebMvcConfigurerAdapter {  

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

}

回答by Pravind Kumar

  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);
       }
    }
    
  1. index.html 文件应该位于以下位置 - src/resources/public/index.html 或 src/resources/static/index.html 如果两个位置都定义了那么首先出现的 index.html 将从该目录调用。
  2. 源代码看起来像 -

    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);
       }
    }
    

回答by ArifMustafa

Inside Spring Boot, I always put the webpages inside a folder like publicor webappsor viewsand place it inside src/main/resourcesdirectory as you can see in application.propertiesalso.

在里面Spring Boot,我总是把网页放在像publicorwebapps或 or这样的文件夹中views,并将它放在src/main/resources目录中,你也可以看到application.properties

Spring_Boot-Project-Explorer-View

Spring_Boot-Project-Explorer-View

and this is my application.properties:

这是我的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

as soon you put the url like servername:15800and this request received by Spring Boot occupied Servlet dispatcher it will exactly search the index.htmland this name will in case sensitive as the spring.mvc.view.suffixwhich would be html, jsp, htm etc.

一旦您输入类似 url 的 urlservername:15800并且 Spring Boot 接收到的这个请求占用了 Servlet 调度程序,它就会精确搜索index.html并且这个名称将区分大小写,因为spring.mvc.view.suffix它是 html、jsp、htm 等。

Hope it would help manyone.

希望它能帮助很多人。

回答by Sampath T

Update: Jan-2019

更新:2019 年 1 月

First create public folder under resources and create index.html file. Use WebMvcConfigurer instead of WebMvcConfigurerAdapter.

首先在资源下创建公共文件夹并创建 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");
    }

}

回答by Yuriy Kiselev

I had the same problem. Spring boot knows where static html files are located.

我有同样的问题。Spring Boot 知道静态 html 文件所在的位置。

  1. Add index.html into resources/static folder
  2. Then delete full controller method for root path like @RequestMapping("/") etc
  3. Run app and check http://localhost:8080(Should work)
  1. 将 index.html 添加到资源/静态文件夹中
  2. 然后删除根路径的完整控制器方法,如@RequestMapping("/") 等
  3. 运行应用程序并检查http://localhost:8080(应该可以)

回答by zappee

If you use the latest spring-boot 2.1.6.RELEASEwith a simple @RestControllerannotation then you do not need to do anything, just add your index.htmlfile under the resources/staticfolder:

如果您使用spring-boot 2.1.6.RELEASE带有简单@RestController注释的最新版本,那么您无需执行任何操作,只需将您的index.html文件添加到resources/static文件夹下:

project
  ├── src
   ?? ├── main
   ??  ?? └── resources
   ??  ??     └── static
   ??  ??         └── index.html

Then hit the URL http://localhost:8080. Hope that it will help everyone.

然后点击 URL http://localhost:8080。希望对大家有所帮助。

回答by Neeraj Gahlawat

You can add a RedirectViewController like:

你可以添加一个 RedirectViewController 像:

@Configuration
public class WebConfiguration implements WebMvcConfigurer {

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