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 {@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/**").addResourceLocations("classpath:/static/","classpath:/templates/");WebMvcConfigurer.super.addResourceHandlers(registry);}
}