seaswalker / posts

0 stars 0 forks source link

Spring boot静态资源配置/打包 #20

Open seaswalker opened 3 years ago

seaswalker commented 3 years ago

在idea社区版下: image 静态资源必须放在webapp下,然后在application.properties中配置:

spring.mvc.view.prefix=/views/
spring.mvc.view.suffix=.html

再写一个view controller:

@Controller
public class ViewController {
    @RequestMapping("/login")
    public String login() {
        return "login";
    }

    @RequestMapping("/index")
    public String index() {
        return "index";
    }
}

然后就可以请求到静态资源了。 打包成直接可以运行的jar包(静态资源也在内)的配置:

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <version>2.4.1</version>
            <executions>
                <execution>
                    <configuration>
                        <mainClass>student.Application</mainClass>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
    <resources>
        <resource>
            <directory>src/main/webapp</directory>
            <targetPath>META-INF/resources</targetPath>
            <includes>
                <include>**/**</include>
            </includes>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
        </resource>
    </resources>
</build>

静态资源必须放在jar包的META-INF下。最后使用命令:

mvn package spring-boot:repackage

之后就可以得到可执行jar包了: image SpringBoot入口方法用了两个注解:

@SpringBootApplication
@EnableAutoConfiguration
public class Application {
    public static void main( String[] args ) {
        SpringApplication.run(Application.class);
    }
}