南国薏米

南国不须收薏苡,百年终竟是芭蕉。

0%

springboot+jsp 打 jar 问题

前情提要】最近做了一个项目,项目是 springboot+jsp 结构的,但是在发布生产环境的时候又需要用 maven 打成 jar 包,但是一开始的默认配置都不成功。下面的文章就是具体的解决过程。


壹、项目结构

贰、异常现象

使用的 JDK 为 1.8,springboot 版本为:

1
2
3
4
5
6
7
8
9
10
11
12
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.RELEASE</version>
<relativePath/>
</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>

打成的 jar 只包含 class 文件,没有见资源文件引入。

叁、解决办法

1. 添加资源路径的映射

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/**</include>
</includes>
<!-- 开启过滤,用指定的参数替换directory下的文件中的参数 -->
<filtering>false</filtering>
</resource>

<resource>
<directory>src/main/webapp</directory>
<targetPath>META-INF/resources</targetPath>
<includes>
<include>**/**</include>
</includes>
</resource>

<resource>
<directory>src/main/java</directory>
<excludes>
<exclude>
**/*.java
</exclude>
</excludes>
</resource>

</resources>

2. 修改 maven 编译版本为 1.4.2

只有使用这个版本打 jar 包才能解析 jsp

3. 设置 mainClass

1
2
3
4
5
6
7
8
9
10
11
<plugins>
<plugin>
<!-- maven插件 -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.4.2.RELEASE</version>
<configuration>
<mainClass>com.gt.LaysshApplication</mainClass>
</configuration>
</plugin>
</plugins>

4. 添加视图配置(可选)

1
2
3
spring.mvc.view.prefix=/WEB-INF/jsp/

spring.mvc.view.suffix=.jsp

下面给出一个比较完整的 maven 编译配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/**</include>
</includes>
<!-- 开启过滤,用指定的参数替换directory下的文件中的参数 -->
<filtering>false</filtering>
</resource>

<resource>
<directory>src/main/webapp</directory>
<targetPath>META-INF/resources</targetPath>
<includes>
<include>**/**</include>
</includes>
</resource>

<resource>
<directory>src/main/java</directory>
<excludes>
<exclude>
**/*.java
</exclude>
</excludes>
</resource>

</resources>
<plugins>
<plugin>
<!-- maven插件 -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.4.2.RELEASE</version>
<configuration>
<mainClass>com.gt.MyApplication</mainClass>
</configuration>
</plugin>
</plugins>
</build>

下面就是修改编译配置之后的结果


【写在后面的话】现代的模板解析引擎已经有了这么多了,为什么不试一下 thymeleaf,但是在最近的项目中碰到了 th:src 标签不解析的问题,目前还不清楚具体原因,而且相同的写法在其他页面都生效,真是怪异啊。鉴于目前还是又很多人使用 springboot+jsp 来进行开发,但是因为使用 IDEA 工具创建的 SpringBoot 项目本身是没有 webapp 目录的。如果我们想要添加 webapp 目录的话,可以手动添加。下面就简单的来说一下配置过程。


1. 点开项目结构管理,点击 IDEA 右上角的 Project Structure

2. 先点击下图中的 + 号,再点击 Web

3. 修改配置

下图是修改配置前的默认配置


下面将 webapp 配置到传统的 main 目录下