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

时间:2014-12-09 14:49:32

标签: java spring spring-boot

我是Java和Spring的新手。 如何将我的应用根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");,但失败了。

10 个答案:

答案 0 :(得分:129)

如果您没有使用@EnableWebMvc注释,它可以开箱即用。当你这样做时,你可以在WebMvcAutoConfiguration中关闭Spring Boot为你做的所有事情。您可以删除该注释,也可以添加回关闭的视图控制器:

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

答案 1 :(得分:41)

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

}

答案 2 :(得分:14)

如果是Spring启动应用程序。

Spring Boot会自动检测public / static / webapp文件夹中的index.html。如果您编写了任何控制器<?php function addNotification(Array $data) { $types = array( 'new' => 0, 'pending' => 1, 'low stock' => 2 ); if (isset($types[$data['type']]) === false) { throw new \InvalidArgumentException('Value for third parameter must be one of new, pending, or low stock.'); } $type = $types[$data['type']]; $query = "SELECT COUNT(*) AS notificationCount FROM storelte_notifications WHERE product_id IN ? AND type = ? "; $previousNotification = $this->db->query($query, array( $data['product_id'], $data['type'] ))->result_array(); if ($previousNotification[0]['notificationCount'] >= 0) { $sql = "INSERT INTO storelte_notifications (message,type,product_id,user_id,timestamp) VALUES(?, ?, ?, ?, ?)"; try { /*foreach ($data as $value) { print_r($value['product_id']); }*/ if (!$this->db->query($sql, array( $data['message'], $data['type'], $data['product_id'], $data['user_id'], $data['timestamp'] ))) { return false; } return true; } catch (Exception $e) { } } else { return true; } } ?> ,它将覆盖默认功能,除非您输入@Requestmapping("/")

,否则它不会显示index.html

答案 3 :(得分:5)

@Configuration  
@EnableWebMvc  
public class WebAppConfig extends WebMvcConfigurerAdapter {  

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

}

答案 4 :(得分:2)

  1. index.html文件应位于以下位置 -    src / resources / public / index.html或    SRC /资源/静态/ 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);
       }
    }
    

答案 5 :(得分:2)

Spring Boot内,我总是将网页放在publicwebappsviews这样的文件夹中,并将其放在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这样的网址和Spring Boot收到的这个请求占用了Servlet调度程序,它将完全搜索index.html,这个名称将以spring.mvc.view.suffix为例敏感。将是html,jsp,htm等。

希望它会对很多人有所帮助。

答案 6 :(得分:2)

更新:2019年1月

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

}

答案 7 :(得分:2)

您可以添加RedirectViewController,例如:

@Configuration
public class WebConfiguration implements WebMvcConfigurer {

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

答案 8 :(得分:0)

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

  1. 将index.html添加到资源/静态文件夹中
  2. 然后删除根路径的完整控制器方法,例如@RequestMapping(“ /”)等
  3. 运行应用并检查http://localhost:8080(应该可以)

答案 9 :(得分:0)

如果您将最新的spring-boot 2.1.6.RELEASE与简单的@RestController注释一起使用,则无需执行任何操作,只需将index.html文件添加到resources/static文件夹下:< / p>

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

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