Spring boot开发web项目

web项目主要是包含一些静态资源(html css js 等)

File -> new -> spring starter project ->设置(选择需要的场景)

1、新建 项目

2、选择web开发场景

因为spring boot是一个jar包,所以静态资源不再存放在webapp中。

静态资源的存放路径通过 org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration类来指定的:

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
...
if (!registry.hasMappingForPattern("/webjars/**")) {
customizeResourceHandlerRegistration(registry
.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/")
.setCachePeriod(getSeconds(cachePeriod))
.setCacheControl(cacheControl));
}
...
}

1、js等第三方静态资源的引入(如:jquery)

目录指定为:classpath:/META-INF/resources/webjars/

webjars官网地址:https://www.webjars.org/

以前引用js的资源,是下载js下载,并放入到webapp目录中,spring boot是将这些资源打包成jar包,使用maven以依赖的形式引入到项目中(pom.xml中配置依赖)

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>jquery</artifactId>
    <version>3.4.0</version>
</dependency>
项目引用时,从jar包目录结构的webjar开始,如:http://localhost:8080/webjars/jquery/3.4.0/jquery.js

2、自己编写的静态资源的使用。

    a、将编写的静态资源打成JAR包引入,与第三方资源的引入相同。如webjars的引入一样。(不推荐)

    b、spring boot将一些静态资源存放目录,即默认的静态资源存放路径。

         在ResourceProperties类中:

 private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
"classpath:/META-INF/resources/", "classpath:/resources/",
"classpath:/static/", "classpath:/public/" };


spring boot默认为我们生成了static静态资源路径,我们可以在static同等 路径中创建public 、resources 、/META-INF/resources。如下:

访问:http://localhost:8080/public.html

         http://localhost:8080/resources.html

         http://localhost:8080/meta-info.html

         http://localhost:8080/static.html

3、欢迎页的设置开发。

     WebMvcAutoConfiguration类中有welcomePageHandlerMapping() ->  getWelcomePage() :

private Optional<Resource> getWelcomePage() {
String[] locations = getResourceLocations(
this.resourceProperties.getStaticLocations());
return Arrays.stream(locations).map(this::getIndexHtml)
.filter(this::isReadable).findFirst();
}
private Resource getIndexHtml(String location) {
return this.resourceLoader.getResource(location + "index.html");
}

即在上面所说的几个静态资源路径中,找到index.html文件,作为欢迎页,如在static目录下添加index.html,在浏览器中输入:http://localhost:8080/ ,即可看到欢迎页

4、网页标签logo的设置

    同上可知,logo的位置是放在 "**/favicon.ico"  中。

5、修改默认静态资源路径:

    在WebMvcAutoConfiguration类中有

         private final ResourceProperties resourceProperties;

     ResourceProperties类中是通过setStaticLocations方法来指定默认的资源路径的,

         private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;

所以需要修改时,使用prefix+属性名来修改staticLocations这个属性。

     @ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties {

...

}

因而,修改默认静态资源路径方法,在application.properties中,添加:

     spring.resources.static-locations=calsspath:/res/,classpath:/img/,classpath:/js/,classpath:/css/
即可。当然修改了属性的值后,原来默认的路径就不再被spring boot识别了,因为是修改属性值,不是添加。

猜你喜欢

转载自blog.csdn.net/zyfzhangyafei/article/details/89764356