springboot工程,无法访问index.html主页

1、问题概述?

我们使用springboot开发了工程后,会将项目打包成jar包或者war包放到服务器端进行发布,但是在打包后,时长会出现index.html主页无法访问的情况。

先分析几种常见的主页无法访问的解决方案,助你解决问题?

1.1、主页的位置放置有误

默认情况下我们需要将主要放置在static目录下,位置不能放置错了,否则无法访问。

如果你的项目使用了thymeleaf,需要将index.html放在templates目录中。

thymeleaf默认的页面在templates目录中。

<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-thymeleaf</artifactId>

</dependency>

1.2、静态页加载有误

一般情况下,静态页面放置在static目录中,但是项目打包后,由于一些特殊包加载的问题,造成了默认目录加载有误,需要在application.yml文件中重新配置一下。

spring:
   resources:
      static-locations: "classpath:/static/"

1.3、项目打包的时候,没有打包静态页面

有些人的项目,打包之后访问不到主页,当去看打包文件中的resources目录的时候,发现里面压根没有页面,当然访问不到。需要在pom.xml中进行如下配置。

需要将你项目中的所有后缀都写上,不写的打包不上。

<resources>
    <resource>
        <directory>src/main/java</directory>
        <includes>
            <include>**/*.xml</include>
        </includes>
    </resource>
    <resource>
        <directory>src/main/resources</directory>
        <includes>
            <include>**/*.yml</include>
            <include>**/*.html</include>
            <include>**/*.js</include>
            <include>**/*.json</include>
            <include>**/*.css</include>
            <include>**/*.png</include>
            <include>**/*.gif</include>
            <include>**/*.eot</include>
            <include>**/*.svg</include>
            <include>**/*.ttf</include>
            <include>**/*.woff</include>
            <include>**/*.woff2</include>
        </includes>
        <!--<filtering>false</filtering>-->
    </resource>

</resources>

项目打包的时候,没有打包静态页面

有些人的项目,打包之后访问不到主页,当去看打包文件中的resources目录的时候,发现里面压根没有页面,当然访问不到。需要在pom.xml中进行如下配置。

需要将你项目中的所有后缀都写上,都则不写的打包不上。

1.4、通过springmvc配置静态资源位置

但是在springboot工程中,一般使用相对较少,但是在一些特殊的环境中,能成功加载就是王道。

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

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/static/","classpath:/templates/");
        WebMvcConfigurer.super.addResourceHandlers(registry);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

雾林小妖

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值