zl程序教程

您现在的位置是:首页 >  后端

当前栏目

springboot 访问静态资源二 (创建web项目)

2023-09-27 14:22:13 时间

一.实现的方式:

1.通过从classpath/static目录下 ,注意必须是static这个目录。

2.servletcontext目录下,在src/main/webapp,目录名称必须要webapp。

注意如果你的应用将被打包成jar,那就不要使用src/main/webapp文件夹。尽管该文件夹是一个共同的标准,但它仅在打包成war的情况下起作用,如果产生一个jar,多数构建工具都会静悄悄的忽略它!所以根据需要进行配置

二.通过servert/context创建webapp目录的web项目

1.新建项目:02-spt-web-res

2.新建pom文件:

        <!--spring boot的启动类 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

3.在src/main下新建webapp/WEB-INF/web.xml 这些目录和文件,同时新建一个index.html文件,

 

4.新建一个config包, 编写GlobalConfig一个全局加载类:

package com.ljf.config;

import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.File;

/**
 * @ClassName: GlobalConfig
 * @Description: TODO
 * @Author: liujianfu
 * @Date: 2020/08/04 19:47:28
 * @Version: V1.0
 **/
@Configuration
public class GlobalConfig {
    @Bean
    public WebServerFactoryCustomizer<TomcatServletWebServerFactory> customizer() {
        System.out.println("初始化配置加载webapp配置!!!!!");
        return (factory) -> {
            factory.addContextCustomizers((context) -> {
                        //模块中webapp相对路径
                        String relativePath = "02-spt-web-res/src/main/webapp";
                        File docBaseFile = new File(relativePath);
                        // 如果路径不存在,则把这个路径加入进去
                        if (docBaseFile.exists()) {
                            context.setDocBase(docBaseFile.getAbsolutePath());
                        }
                    }
            );
        };
    }
}

5.编写启动类

package com.ljf;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * Hello world!
 *
 */
@SpringBootApplication
public class App 
{
    public static void main( String[] args )
    {/**
    * @author liujianfu
    * @description       
    * @date 2020/7/29 0029 上午 9:48
    * @param [args]        
    * @return void
     * 这个程序没有弄成功!!!!
    */
    
        SpringApplication.run(App.class, args);
        System.out.println("启动完成!!!");
    }
}

 6.访问页面