Spring 系列 (1) - 在 Spring Boot 项目里使用 JSP/JSTL 模版和 JQuery+Bootstrap 静态资源


Spring Boot 推荐使用 Thymeleaf 作为其默认视图模板引擎,对于习惯使用 JSP 的老手来说,放弃熟悉的 JSP,还是有点可惜。Spring 作为一个整合大师,可以通过配置来现实使用 JSP 模版。

本文将结合实例讲讲如何在 Spring Boot 项目里使用 JSP、JSTL、JQuery、Bootstrap。

Spring Boot: https://spring.io/projects/spring-boot/
JSP (Java Server Pages): https://www.cnblogs.com/tkuang/p/16027760.html
JSTL (Java server pages standarded tag library,即JSP标准标签库): https://tomcat.apache.org/taglibs/standard/
JQuery: https://jquery.com/
Bootstrap: https://getbootstrap.com/


1. 开发环境

    Windows版本:Windows 10 Home (20H2)   
    IntelliJ IDEA (https://www.jetbrains.com/idea/download/):Community Edition for Windows 2020.1.4
    Apache Maven (https://maven.apache.org/):3.8.1

    注:Spring 开发环境的搭建,可以参考 “ ”。


2. 创建 Spring Boot 项目

    1) 运行 IDEA 创建项目
    
        点击菜单 New 创建 Project:
        
        New Project -> Project Type: Maven -> Project SDK: 1.8 -> Check "Create from archtype" -> select "org.apache.maven.archtypes:maven-archtype-quickstart" -> Next

            Name: SpringbootExample
            GroupId: com.example
            ArtifactId: SpringbootExample

        -> Finish

    2) 生成的项目目录结构

        |-- src
        |   |-- main
        |   |     |-- java
        |   |       |-- com
        |   |            |-- example
        |   |                   |-- App.java
        |   |-- test
        |        |-- java
        |               |-- com
        |                    |-- example
        |                           |-- AppTest.java
        |-- pom.xml

    3) Spring Boot Web 配置
    
        参考 “” 的 “3. 配置 Spring Boot Web” 部分,完成 Spring Boot Web 配置。

        (1) 配置后的 pom.xml

 1             <?xml version="1.0" encoding="UTF-8"?>
 2 
 3             "http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4                 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 5                 4.0.0
 6 
 7                 com.example
 8                 SpringbootExample
 9                 1.0-SNAPSHOT
10 
11                 SpringbootExample
12                 
13                 http://www.example.com
14 
15                 
16                     UTF-8
17                     1.8
18                     1.8
19                 
20 
21                 jar
22 
23                 
24                     org.springframework.boot
25                     spring-boot-starter-parent
26                     2.6.6
27                      
28                 
29 
30                 
31                     
32                         junit
33                         junit
34                         4.11
35                         test
36                     
37                     
38                         org.springframework.boot
39                         spring-boot-starter-web
40                     
41                     
42                     
43                         org.springframework.boot
44                         spring-boot-starter-tomcat
45                         provided
46                     
47                     
48                         org.springframework.boot
49                         spring-boot-starter-test
50                         test
51                     
52                 
53 
54                 
55                     ...
56                 
57             

    在IDE中项目列表 -> SpringbootExample -> 点击鼠标右键 -> Maven -> Reload Project


        (2) 修改 src/main/java/com/example/App.java 文件

 1             package com.example;
 2 
 3             import org.springframework.boot.SpringApplication;
 4             import org.springframework.boot.autoconfigure.SpringBootApplication;
 5 
 6             @SpringBootApplication
 7             public class App {
 8                 public static void main(String[] args) {
 9                     SpringApplication.run(App.class, args);
10                     System.out.println("Spring boot example project");
11                 }
12             }


        (3) 创建 src/main/java/com/example/ServletInitializer.java 文件

 1             package com.example;
 2 
 3             import org.springframework.boot.builder.SpringApplicationBuilder;
 4             import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
 5 
 6             public class ServletInitializer extends SpringBootServletInitializer {
 7 
 8                 @Override
 9                 protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
10                     return application.sources(App.class);
11                 }
12 
13             }


        (4) 创建 src/main/java/com/example/controller/IndexController.java 文件

 1             package com.example.controller;
 2 
 3             import org.springframework.stereotype.Controller;
 4             import org.springframework.web.bind.annotation.RequestMapping;
 5             import org.springframework.web.bind.annotation.ResponseBody;
 6 
 7             @Controller
 8             public class IndexController {
 9                 @ResponseBody
10                 @RequestMapping("/test")
11                 public String test() {
12                     return "Test Page";
13                 }
14             }


        (5) 创建 src/main/resources/application.properties 文件

1             spring.main.banner-mode=off
2 
3             # Web server
4             server.display-name=SpringbootExample-Test
5             server.address=localhost
6             server.port=9090


        (6) 运行

            Edit Configurations

                Click "+" add new configuration -> Select "Maven"

                    Command line: clean spring-boot:run
                    Name: SpringbootExample [clean,spring-boot:run]

                -> Apply / OK

            Click Run "SpringbootExample [clean,spring-boot:run]"

                ...

                Spring boot example project       

            访问 http://localhost:9090/test

                Test Page


3. 导入 Servlet、JSP、JSTL 依赖包

    访问 http://www.mvnrepository.com/,查询 Servlet、JSP、JSTL

    修改 pom.xml:

 1         
 2 
 3             
 4                 ...
 5 
 6                 
 7                 
 8                     org.apache.tomcat.embed
 9                     tomcat-embed-jasper
10                 
11 
12                 
13                 
14                     javax.servlet
15                     javax.servlet-api
16                 
17                 
18                     javax.servlet.jsp
19                     javax.servlet.jsp-api
20                 
21 
22                 
23                 
24                     javax.servlet
25                     jstl
26                 
27      
28                 ...
29             
30 
31         


    在IDE中项目列表 -> SpringbootExample -> 点击鼠标右键 -> Maven -> Reload Project


4. 配置 JSP/JSTL 模版

    1) 在 pom.xml 的 Build 里添加 配置

 1         
 2             ...
 3 
 4             
 5                 
 6                     
 7                         src/main/webapp
 8                         META-INF/resources
 9                         
10                             **/*.*
11                         
12                     
13                     
14                         src/main/resources
15                         
16                         **/*.*
17                         
18                     
19                 
20                 
21                 ...
22             
23         


        注:源文件位置 src/main/webapp,指定编译到 META-INF/resources,指定要把哪些文件编译进去,** 表示 webapp 目录及子目录,*.* 表示所有文件。

    2) 创建 src/main/resources/application.properties 文件

        # 配置 SpringMVC 视图解析器
        spring.mvc.view.prefix=/WEB-INF/jsp/
        spring.mvc.view.suffix=.jsp


        注:其中:/WEB-INF/jsp/ 表示为 src/main/webapp/WEB-INF/jsp/ 目录,在 /WEB-INF/ 目录下的 JSP 模板文件处于保护状态,即禁止通过 http 链接直接访问模板文件。

    3) 创建 src/main/webapp/WEB-INF/jsp/demo.jsp 文件

 1         <%@ page contentType="text/html;charset=UTF-8" language="java"%>
 2         <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
 3         
 4         
 5             Demo
 6         
 7         
 8             

Demo Page

9 10 if test="${not empty msg}"> 11

Message: ${msg}

12
if> 13 14 15


        注:使用 taglib 导入 JSTL core 库。   
    
    4) 修改 src/main/java/com/example/controller/IndexController.java 文件

 1             package com.example.controller;
 2 
 3             import org.springframework.ui.Model;
 4             import org.springframework.stereotype.Controller;
 5             import org.springframework.web.bind.annotation.RequestMapping;
 6             import org.springframework.web.bind.annotation.ResponseBody;
 7 
 8             @Controller
 9             public class IndexController {
10  
11                 @ResponseBody
12                 @RequestMapping("/test")
13                 public String test() {
14                     return "Test Page";
15                 }
16 
17                 @RequestMapping("/demo")
18                 public String demo(Model model) {
19                     model.addAttribute("msg", "Spring Boot 集成 JSP 模板");
20                     return "demo";
21                 }
22 
23             }


    访问:http://localhost:9090/demo

        Demo Page

        Message: Spring Boot 集成 JSP 模板


5. 配置静态资源(jQuery, Bootstrap)

    本文使用 jQuery 3.6.0 和 Bootstrap 4.2.1,两者放到 src/main/resources/static/lib/ 目录下.
    
    1) 目录结构如下

        lib
         |- jquery
         |     |- jquery-3.6.0.min.js
         |
         |- bootstrap-4.2.1-dist
               |- css
               |   |- bootstrap.min.css
               |    ...
               |   
               |- js
                   |- bootstrap.min.js
                    ...

    2) 修改 src/main/webapp/WEB-INF/jsp/demo.jsp 文件

 1         <%@ page contentType="text/html;charset=UTF-8" language="java"%>
 2         <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
 3         <html>
 4         <head>
 5             <title>Demotitle>
 6             <link rel="stylesheet" href="${pageContext.request.contextPath}/lib/bootstrap-4.2.1-dist/css/bootstrap.min.css">
 7             <script language="javascript" src="${pageContext.request.contextPath}/lib/jquery/jquery-3.6.0.min.js">script>
 8             <script language="javascript" src="${pageContext.request.contextPath}/lib/bootstrap-4.2.1-dist/js/bootstrap.min.js">script>
 9         head>
10         <body>
11             <h4>Demo Pageh4>
12 
13             <c:if test="${not empty msg}">
14                 <div class="alert alert-info" role="alert">Message: ${msg}div>
15             c:if>
16             
17             <div class="alert alert-success" role="alert" id="message">div>
18 
19             <script type="text/javascript">
20                 $(document).ready(function(){
21                     console.log("jQuery is running");
22 
23                     $("#message").html("jQuery is running");
24                 });
25             script>
26         body>
27         html>


        注:console.log() 输出信息,可以在浏览器上按 F12 键查看,${pageContext.request.contextPath} 是取得当前站点的 http 根路径。

    访问:http://localhost:9090/demo

        Demo Page

        Message: Spring Boot 集成 JSP 模板
        
        jQuery is running


6. 使用 spring-boot-maven-plugin 插件运行打包

    1) 修改 pom.xml

 1         <project ... >
 2             ...
 3 
 4             <build>
 5                 <finalName>SpringbootExamplefinalName>
 6                 <plugins>
 7                     <plugin>
 8                         <groupId>org.springframework.bootgroupId>
 9                         <artifactId>spring-boot-maven-pluginartifactId>
10                         <configuration>
11                             <mainClass>com.example.AppmainClass>
12                             <layout>JARlayout>
13                         configuration>
14                         <executions>
15                         <execution>
16                             <goals>
17                             <goal>repackagegoal>
18                             goals>
19                         execution>
20                         executions>
21                     plugin>
22                 plugins>
23                 ...
24             build>
25         project>


        layout 属性用来指定打成 jar 还是 war 文件,可用的值包括:ZIP 、JAR 、WAR、 NONE

        在IDE中项目列表 -> SpringbootExample -> 点击鼠标右键 -> Maven -> Reload Project

    2) 打包 jar

        菜单 View -> Tool Windows -> Maven -> SpringbootExample -> Lifecycle -> Clean & Package

        jar 包生成在目录 target/ 里

            SpringbootExample.jar
            SpringbootExample.jar.original  

        注:SpringbootExample.jar  包含依赖包,可以直接运行。 SpringbootExample.jar.original 里不包含依赖的包(要手动配置依赖环境),运行前要把文件名上的 “.original” 去掉。

        点击 IDEA 底部 Terminal 标签页,执行如下命令。

        $ java -jar target/SpringbootExample.jar

            ...

            Spring boot example project       

        访问 http://localhost:9090/test

            Test Page

    3) 打包 war

        把 pom.xml 里 jar 改成 war, spring-boot-maven-plugin 的 layout 属性改成 WAR,并把 spring-boot-starter-tomcat 依赖注释掉。

        菜单 View -> Tool Windows -> Maven -> SpringbootExample -> Lifecycle -> Clean & Package

        war 包生成在目录 target/ 里

            SpringbootExample.war
            SpringbootExample.war.original

        把 SpringbootExample.war 放到独立运行的 Tomcat 的 webapp 目录下,假设 Tomcat 运行在 8080 端口。
        
        访问 http://localhost:8080/SpringbootExample/Test

            Test Page