去年(即2017年)大家都在说SpringBoot这好那好。我也就在前两天稍微了解下它。

学新技术当然得去官方网站,其实官网的Getting Start说的够入门了。首先SpringBoot也是基于Spring的,所以有些东西是相通的。而了解一个新技术,个人认为应该带着“它能做什么”的目的去学习。理论上说,SpringBoot能做到Spring所能做的任何!

我想使用SpringBoot的原因很简单,就是因为它可以main方法启动一个web项目(其实maven的jetty插件也可以,但jetty插件对单个web项目支持地不错,但是对包含其它jar的web项目支持不是很好,这是我个人真实体会)。

先把目标放在最上边,看完本博客,你将会了解到:

  • 第一个SpringBoot项目
  • 如何访问thymeleaf页面、页面文件的位置
  • 如何显示图片
  • 如何引入外部js/css
  • 如何发送ajax请求(拼凑url)
  • 如何使用JdbcTemplate
  • 如何使用使用DAO
  • 如何显示Spring中的所有Bean
  • 如何使用Logback、指定其路径
  • !如何打印SQL
  • SpringBoot有时说thymeleaf页面有错误,但是控制层没有打印出任何错误信息

要是没有想要的内容,就不用花费时间往下看了。

第一个SpringBoot项目

之前(具体日期是2018-05-30)我在官网看到有Getting Started,而今天(2018-06-11)再看,竟然因为网站改版找不到了。不过不影响本博客的内容。

第一个SpringBoot项目得基于maven,我们先创建一个pom.xml,其内容如下

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.billy</groupId>
    <artifactId>springboot-demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.2.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
</project>

然后在src/main/java下新建一个类hello.SampleController,如下

package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@EnableAutoConfiguration
public class SampleController {

    @RequestMapping("/")
    @ResponseBody
    String home() {
        return "Hello World!";
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(SampleController.class, args);
    }
}

然后启动该类,在浏览器中访问 http://127.0.0.1:8080 就可以看到Hello World!了,很简单吧。

然后我们就要添加其它功能了。

如何访问页面

了解SpringMVC+JSP的都知道SpringMVC使用视图解析器(ViewResolver)来跳转到jsp页面,同样地,它应该在SpringBoot中也适用,可是我有网上查了两个小时关于SpringBoot jsp的资料,在我本地没有成功一次,就索性使用thymeleaf模板引擎了。

要使用thymeleaf,需要如下几个步骤:

  • 添加依赖
  • 配置thymeleaf
  • 创建页面
  • 添加Controller跳转

第一步,需要在pom.xml中添加依赖

       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
       </dependency>

第二步,需要在src/main/resources下新建application.properties文件,SpringBoot也支持使用application.yml,个人喜欢用前者。application.properties的内容如下:

spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.cache=false

第三步,在src/main/resources下新建文件夹templates,在里面放个index.html,可以先写上简单的HelloWorld.

<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title>主页</title>
</head>
<body>
<h3>Hello, World,这是主页</h3>
</body>
</html>

第四步,添加controller跳转,可在SampleController中添加

    @RequestMapping("/index")
    String login() {
        System.out.println("index");
        return "index";
    }

至此即可访问到页面。需要说明的是templates文件夹的名字可以是static、public,SpingBoot默认加载从这几个位置下加载页面,注意这些文件夹的位置在src/main/resources下。我的习惯是templates里存放页面,static下存在静态资源如js/css/image等,以后我们就遵守这种约定。

如何显示图片

上面我们说过图片的位置在src/main/resources/static/image下,那我们随便复制一张图片如goal.png,那么在index.html页面内就可以使用如下来加载并显示一张图片

<img th:src="@{/image/goal.png}"/>

这样SpringBoot会自动从static/templates/public下寻找image/goal.png。

如何引入外部js/css

和显示图片功能类似,我们先复制一个js文件到src/main/resources/static/js下,如jquery-1.7.1.min.js,那么在index.html页面内可以使用如下代码来加载js

    <script type="text/javascript" th:src="@{/js/jquery-1.7.1.min.js}"></script>

道理在显示图片类似,SpringBoot会自动在static/templates/public下寻找js/jquery-1.7.1.min.js。

加载css和加载js完全一样,如

    <link rel="stylesheet" th:href="@{/css/style.css}"/>

如何发送ajax请求(拼凑url)

一个Web项目中不发送ajax请求就显得很不正常啊。而要发送一个请求,最主要是参数是当前项目的地址,在jsp中可以使用${pageContext.request.contextPath}或<%=request.getContextPath()%>来获取。而在thymeleaf中则可以使用 [[${#request.contextPath}]]来获取,如:

    var basePath = [[${#request.contextPath}]];
    $.ajax({
        url : basePath + '/aaa/bbb/cccc',
        type : 'POST',
        data : {},
        dataType : 'JSON',
        success : function(data) {
            alert(data);
        }
    });

看着奇怪吧?